2013-05-31 53 views
0

在一個可執行文件。特等我有以下幾點:印刷比賽中文件的每一行的第一個實例(Perl的)

#!/usr/bin/env perl 
$file = 'TfbG_peaks.txt'; 
open(INFO, $file) or die("Could not open file."); 

foreach $line (<INFO>) { 
     if ($line =~ m/[^_]*(?=_)/){ 
       #print $line; #this prints lines, which means there are matches 
       print $1; #but this prints nothing 
     } 
} 

基於我在http://goo.gl/YlEN7http://goo.gl/VlwKe閱讀,print $1;應打印在第一場比賽中每條線,但它不。幫幫我!

回答

2

不,$1應打印由所謂的capture groups(由包圍構造 - (...)創建)保存的字符串。例如:

if ($line =~ m/([^_]*)(?=_)/){ 
    print $1; 
    # now this will print something, 
    # unless string begins from an underscore 
    # (which still matches the pattern, as * is read as 'zero or more instances') 
    # are you sure you don't need `+` here? 
} 

在原始代碼的模式沒有任何捕捉組,這就是爲什麼$1是空的(undef,要準確)那裏。並且(?=...)不算,因爲這些用於添加預見子表達式。

+0

感謝您的快速,友好和翔實的迴應! – mmkstarr

0

$1打印捕獲模式中的第一個捕獲((...))。

也許你在想的

print $& if $line =~ /[^_]*(?=_)/; # BAD 

print ${^MATCH} if $line =~ /[^_]*(?=_)/p; # 5.10+ 

但是下面會更簡單(和5.10之前的工作):

print $1 if $line =~ /([^_]*)_/; 

注意:如果模式不匹配,則會得到性能提升您可以添加領先的^(?:^|_)(以適用者爲準)。

print $1 if $line =~ /^([^_]*)_/; 
+0

謝謝!這絕對有助於我更好地學習Perl。 – mmkstarr

相關問題