我有一个目录,其中包含该格式的图像头文件列表
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.有没有更有效的方法呢?
在一些实用程序模块的帮助下,这很简单
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';
| 归档时间: | 
 | 
| 查看次数: | 543 次 | 
| 最近记录: |