
FishMonger
Veteran
Oct 6, 2008, 2:03 PM
Post #5 of 6
(3248 views)
|
|
Re: [maestria] frequency count of words...
[In reply to]
|
Can't Post
|
|
In addition to the unnecessary if/else block that Kevin pointed out, there's also no reason/need to use the @arr array. Why are you using -l for no reason? Every Perl script you write should include the following 2 pragmas.
use strict; use warnings; Since Perl 5.6 the recommended and best practice is to use a lexical var for the filehandle instead of the bareword and you shold use the 3 arg form of open. Also, you should ALWAYS check the return code of an open call and take action if it fails. Part of that action would be to include in the error message the reason it failed i.e., the value in the $! var. open my $FILE, '<', 'test' or die "can't open 'test' $!";
while($line=<FILE>){ better written as: while( my $line = <$FILE> ) {
chomp $line; @arr=split(/ /,$line); foreach $var(@arr){ if(exists $ansresult{$var}){ $ansresult{$var}++; } else{ $ansresult{$var}=1; } } } Better written as:
chomp ($line); $ansresult{$_}++ for split /\s+/, $line; while(($value,$key)=each %ansresult){ print "$value Appears $key times"; } better writtten as
while( my ($key, $value) = each %ansresult ) { print "$key Appears $value times\n"; Complete script:
#!/usr/bin/perl use strict; use warnings; my %ansresult; open my $FILE, '<', 'report' or die "can't open 'test' $!"; while( my $line = <$FILE> ) { next if $line =~ /^\s*$/; # I added this just incase there where blank lines. chomp $line; $ansresult{$_}++ for split /\s+/, $line; } while( my ($key, $value) = each %ansresult ) { print "$key Appears $value times\n"; }
(This post was edited by FishMonger on Oct 6, 2008, 2:07 PM)
|