1

我有一个目录,其中包含格式的图像头文件列表

image1.hd
image2.hd
image3.hd
image4.hd

我想在目录中搜索正则表达式Image type:=4并找到第一次出现此模式的文件号。我可以在 bash 中使用几个管道轻松地做到这一点:

 grep -l 'Image type:=4' image*.hd | sed ' s/.*image\(.*\).hd/\1/' | head -n1

在这种情况下返回 1。

此模式匹配将在 perl 脚本中使用。我知道我可以使用

my $number = `grep -l 'Image type:=4' image*.hd | sed ' s/.*image\(.*\).hd/\1/' | head -n1`

但在这种情况下最好使用纯 perl 吗?这是我能想到的最好的使用 perl 的方法。非常麻烦:

my $tmp;
#want to find the planar study in current study
  foreach (glob "$DIR/image*.hd"){
    $tmp = $_;
    open FILE, "<", "$_" or die $!;
    while (<FILE>)
      {
    if (/Image type:=4/){
      $tmp =~ s/.*image(\d+).hd/$1/;
    }
      }
    close FILE;
    last;
  }
 print "$tmp\n";

这也返回所需的输出 1。有没有更有效的方法来做到这一点?

4

1 回答 1

5

借助几个实用模块,这很简单

use strict;
use warnings;

use File::Slurp 'read_file';
use List::MoreUtils 'firstval';

print firstval { read_file($_) =~ /Image type:=4/ } glob "$DIR/image*.hd";

但是,如果您仅限于核心 Perl,那么这将满足您的要求

use strict;
use warnings;

my $firstfile;
while (my $file = glob 'E:\Perl\source\*.pl') {
    open my $fh, '<', $file or die $!;
    local $/;
    if ( <$fh> =~ /Image type:=4/) {
        $firstfile = $file;
        last;
    }
}

print $firstfile // 'undef';
于 2013-04-03T14:06:34.800 回答