如何用脚本中的Perl替换文件中的字符串(不在命令行中)

use*_*289 0 regex shell scripting perl

我想替换文件中的字符串.我当然可以用

 perl -pi -e 's/pattern/replacement/g' file
Run Code Online (Sandbox Code Playgroud)

但是我想用脚本来做.

还有其他方法可以做到system("perl -pi -e s/pattern/replacement/g' file")吗?

Sch*_*ern 5

-i利用您仍然可以读取未链接的文件句柄,您可以看到它在perlrun中使用的代码.自己做同样的事情.

use strict;
use warnings;
use autodie;

sub rewrite_file {
    my $file = shift;

    # You can still read from $in after the unlink, the underlying
    # data in $file will remain until the filehandle is closed.
    # The unlink ensures $in and $out will point at different data.
    open my $in, "<", $file;
    unlink $file;

    # This creates a new file with the same name but points at
    # different data.
    open my $out, ">", $file;

    return ($in, $out);
}

my($in, $out) = rewrite_file($in, $out);

# Read from $in, write to $out as normal.
while(my $line = <$in>) {
    $line =~ s/foo/bar/g;
    print $out $line;
}
Run Code Online (Sandbox Code Playgroud)

  • 那不够容易吗?!把它放在一个函数中. (3认同)