打印以文本和计数开头的特定单词

时间:2014-05-09 12:37:51

标签: arrays perl

我喜欢用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};
}

但是在循环变量上显示缺少$的错误 任何人都可以帮助我解决我想念的问题。 感谢。

1 个答案:

答案 0 :(得分:0)

这应该产生output.txt的所需输出,其中包含出现顺序的单词

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});
}