我正在学习 Perl 并编写了一个小脚本来打开 perl 文件并删除注释# Will remove this comment
my $name = ""; # Will not remove this comment
#!/usr/bin/perl -w
<- 不会删除此特殊注释
要编辑的文件的名称通过终端作为参数传递
die "You need to a give atleast one file-name as an arguement\n" unless (@ARGV);
foreach (@ARGV) {
$^I = "";
(-w && open FILE, $_) || die "Oops: $!";
/^\s*#[^!]/ || print while(<>);
close FILE;
print "Done! Please see file: $_\n";
}
现在,当我通过终端运行它时:
perl removeComments file1.pl file2.pl file3.pl
我得到了输出:
Done! Please see file:
这个脚本完全按照我的预期工作,但
问题 1:为什么
$_
没有打印文件名?问题 2:既然循环运行了 3 次,为什么
Done! Please see file:
只打印一次?您将如何用尽可能少的行编写此脚本?
如果你有时间,也请评论我的代码。
谢谢你。
最佳答案
while 将菱形运算符 <> 读取的行存储到 $_ 中,因此您正在写入存储文件名的变量。
另一方面,您使用 open
打开文件。但实际上不要使用句柄来阅读;它使用空菱形运算符代替。空菱形运算符对 @ARGV
中的文件进行隐式循环, 删除文件名,所以 foreach
只运行一次。
要解决第二个问题,您可以使用 while(<FILE>)
,或重写循环以利用 <>
中的隐式循环并将整个程序编写为:
$^I = "";
/^\s*#[^!]/ || print while(<>);
关于perl - foreach 和特殊变量 $_ 未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17463357/