2014-10-06 87 views
0

比較數字我有文件的內容爲:讀括號內的內容,並在Perl

(0872) "ss_current" (1 of 1) 
(0873) "ss_current_6oct" (0 of 1) 

我想讀文件的每一行,然後得到最後括號中的內容即

(1 of 1) 
(0 of 1) 

並比較數字,如果它們相等,即「之前」和「之後」的數字相等。 我的代碼:

my @cs; 
while (<$fh>) { 
    if ($_ =~ /\((.*?)\)/) { 
     my $temp = $1; 
     print $temp, "\n"; 
    } 
} 

但是,這給內容08720873

回答

0
use strict; 
use warnings; 

open my $in, '<', 'in.txt'; 

while(<$in>){ 
    chomp; 
    my ($first, $second) = /\((\d+) of (\d+)\)/; 
    print "$first of $second\n" if $first == $second; 
} 
5

你的正則表達式只拿起第一組括號中。說得具體些,你可以挑選(1 of 1)(0 of 1)

while (<$fh>) { 
    # \d+ means match one or more adjacent numbers 
    # brackets capture the match in $1 and $2 
    if ($_ =~ /\((\d+) of (\d+)\)/) { 
     if ($1 == $2) { 
      # they are equal! print out the line (or do whatever) 
      # (the line is set to the special variable $_ while processing the file) 
      print "$_"; 
     } 
    } 
} 
0

你的正則表達式是不夠具體,因爲有一組以上的每一行括號。

可以使用正則表達式來匹配您想要的確切條件,使用backreferences

use strict; 
use warnings; 

while (<DATA>) { 
    print if /\((\d+) of \1\)/; 
} 

__DATA__ 
(0872) "ss_current" (1 of 1) 
(0873) "ss_current_6oct" (0 of 1) 

輸出:

(0872) "ss_current" (1 of 1) 

注意,這是一種先進的技術,作爲一個必須確保強制執行的邊界條件,以避免不希望的方式相匹配的字符串。出於這個原因,如果你是初學者,我實際上推薦使用一種技術,比如警告外星人使用。