【问题标题】:Can I skip a whole file with the <> operator?我可以使用 <> 运算符跳过整个文件吗?
【发布时间】:2010-11-28 04:07:36
【问题描述】:

下面的 Perl 代码有一个明显的低效率;

while (<>)
{
if ($ARGV =~ /\d+\.\d+\.\d+/) {next;}
... or do something useful
}

代码将遍历我们不需要的文件的每一行。

关于运行这个特定脚本的文件的大小,这不太可能产生明显的差异,但为了学习;我怎样才能将整个文件 正在工作并移至下一个文件?

这样做的目的是因为这个脚本运行的服务器存储了旧版本的应用程序,文件名中有版本号,我只对当前版本感兴趣。

【问题讨论】:

    标签: perl argv diamond-operator


    【解决方案1】:

    如果您可以在开始阅读任何文件之前过滤 @ARGV,那么 Paul Roub 的解决方案是最好的。

    如果您在开始迭代后必须跳过文件,

    while (<>) {
        if (/# Skip the rest of this file/) {
            close ARGV;
            next;
        }
        print "$ARGV: $_";
    }
    

    【讨论】:

    • 我喜欢这个。这样您就可以轻松地通过关键字搜索目录中的文件:perl -E'@ARGV=&lt;"*"&gt;; while(&lt;&gt;){if (/searchedWord/){say $ARGV; close ARGV;}}'
    【解决方案2】:

    先grep ARGV。

    @ARGV = grep { $_ !~ /\d+\.\d+\.\d+/ } @ARGV;
    
    while (<>)
    {
      # do something with the other files
    }
    

    【讨论】:

    • IC,您只需像过滤任何其他列表一样过滤@ARGV。
    【解决方案3】:

    Paul Roub 的answer 工作以获取更多信息,请参阅The IO operators section of perlop man page。提到了使用 grep 的模式以及与 相关的一些其他事情。

    请注意提及ARGV::readonly 的内容如下:

    perl dangerous.pl 'rm -rfv *|'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2017-10-23
      • 2014-01-02
      • 2022-12-11
      • 1970-01-01
      • 2021-09-11
      • 2023-03-15
      相关资源
      最近更新 更多