【问题标题】:Use parameters as regex in Perl在 Perl 中使用参数作为正则表达式
【发布时间】:2016-04-24 16:12:22
【问题描述】:

我得到一个正则表达式作为我的脚本的参数。就像/stat.*\.log/一样。

我尝试将它与 Perl 的内置 grep 一起使用。

my @dots = readdir($dh);
@dots=grep($conf->{classifier_regx}, @dots);

其中@dots 是一个包含文件和子文件夹的完整目录。 $conf->{classifer_regx} 是提供参数的正则表达式。

实际上,这会返回所有文件和子文件夹。是否可以在运行时对值进行 grep?我怎样才能做到这一点?我错过了什么?手册页?

【问题讨论】:

  • my $value = $conf->{classifier_regx}; grep(/$value/, @dots);?
  • 好的,这项工作。但为什么我不能做grep(/$conf->{classifier_regx}/, @dots); 他给了所有子文件夹和文件。总之感谢 ! 编辑:没关系,我应该做错了什么。旧线也可以工作。
  • 不客气。原来的第一个参数中缺少//

标签: regex perl parameter-passing


【解决方案1】:

我认为您的grep 中缺少//

@dots = grep(/$conf->{classifier_regx}/, @dots);

如果还是不行,可以试试

my $value = $conf->{classifier_regx};
@dots = grep(/$value/, @dots);

【讨论】:

    【解决方案2】:

    如果您使用的是 Bash 脚本,则要容易得多,因为您可以在脚本上使用 grep。但是,由于您使用的是 Perl,您可以执行以下操作:

    my @dots = readdir($dh);
    
    $str = <STDIN>; //This will allow you to enter a string at runtime
    chomp str;
    
    foreach $i (@dots) { // Iterate through the array. If a value is found, print it
        if ($i eq $str) {
            print "$str";
        }
    }
    

    【讨论】:

    • 我不知道你在说什么,Perl 赢了grep
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多