Chinaunix首页 | 论坛 | 博客
  • 博客访问: 450559
  • 博文数量: 45
  • 博客积分: 2526
  • 博客等级: 少校
  • 技术积分: 478
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-12 21:04
文章分类

全部博文(45)

文章存档

2014年(1)

2011年(1)

2010年(3)

2009年(22)

2008年(18)

我的朋友

分类:

2010-06-30 17:17:33

we usually this command to edit some lines in file:

perl -pi -e 's/old_var/new_var/g' filename
  or generate a backup file:
perl -pi'.bak' -e 's/old_var/new_var/g' filename   #(backup name is filename.bak)
perl -pi'*_another_name' -e 's/old_var/new_var/g'

The former one will get backup file named "filename.bak", the latter one is
"filename_another_name", which means (see perldoc perlrun for details):

If the extension doesn't contain a "*", then it is appended to the
end of the current filename as a suffix.  If the extension does
contain one or more "*" characters, then each "*" is replaced with
the current filename.  In Perl terms, you could think of this as:

Now, we met this problem: how to edit file within a perl script??
Normally, the equivalent codes with the above commnads are like:

#!/usr/bin/perl

$^I = ".bak";
while(<>) {
    if ($_ =~ /old_var/) {
        s/old_var/new_var/g;
    }
}


Supposed the script name is 'test.pl', we run it like this:
    perl test.pl filename
which will be equivalent with the above one line perl command.

To avoid giving input filename to the script, we simply add this line:
    @ARGV = ("filename");

#!/usr/bin/perl
$^I = ".bak";
@ARGV = ("filename");
while(<>) {
    if ($_ =~ /old_var/) {
        s/old_var/new_var/g;
    }
}


At last, I have to say that we don't need to do it in such a way, please
try this Perl module: . which is easy to use.

阅读(4502) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~