use strict; use warnings; use File::Copy; foreach $_ (@ARGV) { my $orig = $_; (my $copy = $orig) =~ s/\.js$/_extjs4\.js/; copy($orig,$copy) or die(qq{Failed to copy $orig -> $copy}); }
现在我有了名为“* _extjs4.js”的文件,我想将它们传递给一个脚本,该脚本同样从命令行获取文件名,并进一步处理这些文件中的行.到目前为止,我能够成功获得文件句柄,如下面的脚本,它的输出显示:
use strict; use warnings; foreach $_ (@ARGV) { print "$_\n"; open(my $fh,"+>",$_) or die $!; print $fh; #while (my $line = <$fh>) { # print $line; #} close $fh; }
哪些产出(部分):
./filetree_extjs4.js GLOB(0x1a457de8) ./async_submit_extjs4.js GLOB(0x1a457de8)
我真正想做的是,而不是打印文件句柄的表示,是使用文件本身的内容.一个开始是打印文件行,我试图用上面注释掉的代码.
但是该代码没有效果,文件的行不会打印出来.我究竟做错了什么? $_用于处理命令行参数和用于处理文件内容的参数之间是否存在冲突?
解决方法
print $fh返回GLOB(0x1a457de8)的原因是因为标量$fh是文件句柄而不是文件本身的内容.要访问文件本身的内容,请使用< $fh>.例如:
while (my $line = <$fh>) { print $line; } # or simply print while <$fh>;
这在pelrdoc perlop
中记录:
If what the angle brackets contain is a simple scalar variable (e.g.,
<$foo>
),then that variable contains the name of the filehandle to
input from,or its typeglob,or a reference to the same.
但它已经尝试过了!
我知道.将打开模式更改为< ;.
How come when I open a file read-write it wipes it out?
Because you’re using something like this,which truncates the file
then gives you read-write access:06001
Whoops. You should instead use this,which will fail if the file
doesn’t exist:06002
Using
">"
always clobbers or creates. Using"<"
never does either. The"+"
doesn’t change this.
不言而喻,或者死!开放后强烈推荐.
但退后一步.
有一种更多的Perlish方式来备份原始文件并随后对其进行操作.实际上,它可以通过命令行本身(!)使用-i标志来实现:
$perl -p -i._extjs4 -e 's/foo/bar/g' *.js
有关详细信息,请参见perldoc perlrun
.
我不能满足我的需求到命令行.
如果操作对于命令行来说太多了,那么Tie::File
模块值得一试.