【问题标题】:Perl oneliner where slurps @ARGVPerl oneliner 在哪里啜饮@ARGV
【发布时间】:2023-04-09 21:43:01
【问题描述】:

我正在寻找一个 Perl oneliner(将其插入到 Bash 脚本中),我需要下一个接口:

perl -0777 -nlE 'commands' file1 file2 .... fileN

我创建了下一个:

perl -0777 -lnE 'BEGIN{$str=quotemeta(do{local(@ARGV, $/)="file1"; <>})} say "working on $ARGV" if $_ =~ /./' "$@"

更漂亮:

perl -0777 -lnE '
    BEGIN{
        $str = quotemeta(
            do{
                local(@ARGV, $/)="file1"; <>  #localize ARGV to "file1.txt" for <>
            }
        )
    }
    say "working on $ARGV" if $_ =~ /./   #demo only action
' "$@"

它可以工作,但是每次需要更改file1时,我都需要编辑源代码。

如何将脚本更改为以下内容?

  • $ARGV[0](file1)插入$str(在BEGIN块中)
  • 然后在主循环中将其他参数添加到 $_

【问题讨论】:

    标签: perl


    【解决方案1】:

    将其作为参数传递,将其从 BEGIN 块中的 @ARGV 中删除。

    $ echo foo >refile
    
    $ echo -ne 'foo\nbar\nfood\nbaz\n' >file1
    
    $ echo -ne 'foo\nbar\nfood\nbaz\n' >file2
    
    $ perl -lnE'
       BEGIN {
          local @ARGV = shift(@ARGV);
          $re = join "|", map quotemeta, <>;
       }
       say "$ARGV:$.:$_" if /$re/;
       close(ARGV) if eof;  # Reset $.
    ' refile file1 file2
    file1:1:foo
    file1:3:food
    file2:1:foo
    file2:3:food
    

    【讨论】:

    • 赋值运算符在其 LHS 操作数之前评估其 RHS 操作数。它允许 perl -E'my $x="abc"; { my $x = uc($x); say $x; } say $x;' 之类的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多