2013-04-03 61 views
0

模式的第一次出现我与格式Perl的搜索目录

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

这是一对夫妇的工具模块的帮助下

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

优秀的感谢 – moadeep