2014-05-09 36 views
0

我喜歡用sid = word和sid = text來找到單詞開頭並打印並將它計爲同一單詞。在文本中打印特定單詞並計數

sid=word 2 
sid=text 5 

我嘗試做一些腳本

use warnings; 
use strict; 

my $input = 'input.txt'; 
my $output = 'output.txt'; 

open (FILE, "<", $input) or die "Can not open $input $!"; 
open my $out, '>', $output or die "Can not open $output $!"; 

while (<FILE>){ 
    foreach my @arr = /(?: ^|\s)(sid=\S*) { 
     $count{$arr}++; 
    } 
} 

foreach my @arr (sort keys %count){ 
    printf "%-31s %s\n", $str, $count{$arr}; 
} 

但顯示錯誤的循環變量$失蹤 任何人都可以幫助我什麼,我錯過了。 謝謝。

+0

的順序它說在那裏產生期望的輸出output.txt,用言語?哪條線? – AntonH

+0

是的,它說線13完全在 - > foreach我的@ arr – skippyman

+0

除非我錯了,你通過默認變量'$ _'拆分循環,是嗎?如果你使用'foreach my $ arr(split /(?:^| \ s)(sid = \ S *)/){'? – AntonH

回答

0

這應該在外觀

use warnings; 
use strict; 

my $input = 'input.txt'; 
my $output = 'output.txt'; 

open (my $FILE, "<", $input) or die "Can not open $input $!"; 
open (my $out, ">", $output) or die "Can not open $output $!"; 

my (%count, @arr); 
while (<$FILE>){ 
    if (/(?: ^|\s)(sid=\S*)/x) { 
     push @arr, $1 if !$count{$1}; 
     $count{$1}++; 
    } 
} 

foreach my $str (@arr) { 
    print $out sprintf("%-31s %s\n", $str, $count{$str}); 
} 
+0

現在的工作,感謝您的幫助。真的很感激。 – skippyman

+0

Thanks @mpapec ... – skippyman

相關問題