2013-04-03 60 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