我想知道Perl在使用选项perl -pi -e执行时所运行的等效代码是什么?
关于一些这样的问题,我可以读到:
while (<>) {
... # your script goes here
} continue {
print;
}但此示例没有显示保存文件的部分。
Perl是如何确定EOL的?当没有发生任何更改时,它会触摸文件吗?例如,如果我有一个旧的MAC文件(仅\r)。它如何处理s/^foo/bar/gm
我试着使用Perl调试器,但它并没有真正的帮助。所以我只是想猜一下:
#!/usr/bin/env perl
my $pattern = shift;
map &process, @ARGV;
# perl -pi -e PATTERN <files>...
sub process {
next unless -f;
open my $fh, '<', $_;
my $extract;
read $fh, $extract, 1024;
seek &fh, 0, 0;
if ($extract =~ /\r\n/) {
$/ = "\r\n";
} elsif ($extract =~ /\r[^\n]/) {
$/ = "\r";
} else {
$/ = "\n";
}
my $out = '';
while(<&fh>) {
my $__ = $_;
eval $pattern;
my $changes = 1 if $_ ne $__;
$out .= $_;
}
if($changes)
{
open my $fh, '>', $_;
print $fh $out;
}
close &fh;
}发布于 2015-01-25 10:17:50
您可以检查Perl实际使用的代码和核心模块B::Deparse。这个编译器后端模块是用选项-MO=Deparse激活的。
$ perl -MO=Deparse -p -i -e 's/X/U/' ./*.txt
BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
s/X/U/;
}
continue {
die "-p destination: $!\n" unless print $_;
}
-e syntax OK因此perl正在遍历给定文件中的行,执行将$_设置为行的代码,并打印出结果的$_。
魔术变量$^I被设置为空字符串。这打开了就地编辑。就地编辑在perldoc中解释。没有检查该文件是否未更改。因此,修改后的文件的时间总是被更新的。显然,备份文件的修改时间与原始文件的修改时间相同。
使用-0标志,您可以设置输入记录分隔符,以便对Mac文件使用"\r“。
$ perl -e "print qq{aa\raa\raa}" > t.txt
$perl -015 -p -i.ori -e 's/a/b/' t.txt
$cat t.txt
ba
$ perl -MO=Deparse -015 -p -i.ori -e 's/a/b/'.txt
BEGIN { $^I = ".ori"; }
BEGIN { $/ = "\r"; $\ = undef; }
LINE: while (defined($_ = <ARGV>)) {
s/a/b/;
}
continue {
die "-p destination: $!\n" unless print $_;
}
-e syntax OK发布于 2015-01-25 00:04:23
来自perlrun文档
-p assumes an input loop around your script. Lines are printed.
-i files processed by the < > construct are to be edited in place.
-e may be used to enter a single line of script. Multiple -e commands may be given to build up a multiline script.https://stackoverflow.com/questions/28131528
复制相似问题