Perl搜索目录中第一个出现的模式

Perl搜索目录中第一个出现的模式,perl,grep,Perl,Grep,我有一个目录,其中列出了该格式的图像头文件 image1.hd image2.hd image3.hd image4.hd 我想在目录中搜索正则表达式映像类型:=4,并找到第一次出现此模式的文件号。在bash中,我可以使用两个管道轻松实现这一点: grep -l 'Image type:=4' image*.hd | sed ' s/.*image\(.*\).hd/\1/' | head -n1 在本例中返回1 此模式匹配将在perl脚本中使用。我知道我可以用 my $number =

我有一个目录,其中列出了该格式的图像头文件

image1.hd
image2.hd
image3.hd
image4.hd
我想在目录中搜索正则表达式映像类型:=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。有没有更有效的方法可以做到这一点?

这在几个实用模块的帮助下很简单

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';

在几个实用模块的帮助下,这很简单

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';