加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 打开通过$_命令行提供的文件名是否存在问题?

发布时间:2020-12-16 06:18:31 所属栏目:大数据 来源:网络整理
导读:我无法修改处理作为命令行参数传递的文件的脚本,仅用于复制这些文件,另外修改这些文件.以下perl脚本适用于复制文件: use strict;use warnings;use File::Copy;foreach $_ (@ARGV) { my $orig = $_; (my $copy = $orig) =~ s/.js$/_extjs4.js/; copy($orig
我无法修改处理作为命令行参数传递的文件的脚本,仅用于复制这些文件,另外修改这些文件.以下perl脚本适用于复制文件:

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.

但它已经尝试过了!

我知道.将打开模式更改为&lt ;.

根据perldoc perlfaq5

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模块值得一试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读