CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions: Re: [maestria] frequency count of words...: Edit Log



FishMonger
Veteran / Moderator

Oct 6, 2008, 2:03 PM


Views: 12159
Re: [maestria] frequency count of words...

In addition to the unnecessary if/else block that Kevin pointed out, there's also no reason/need to use the @arr array.


Code
#!/usr/bin/perl -l

Why are you using -l for no reason?

Every Perl script you write should include the following 2 pragmas.

Code
use strict; 
use warnings;


Code
open(FILE,"test");

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' $!";


Quote
while($line=<FILE>){

better written as:
while( my $line = <$FILE> ) {


Code
        chomp $line; 
@arr=split(/ /,$line);
foreach $var(@arr){
if(exists $ansresult{$var}){
$ansresult{$var}++;
}
else{
$ansresult{$var}=1;
}
}
}

Better written as:

Code
        chomp ($line); 
$ansresult{$_}++ for split /\s+/, $line;


Code
while(($value,$key)=each %ansresult){ 
print "$value Appears $key times";
}

better writtten as

Code
while(  my ($key, $value) = each %ansresult ) { 
print "$key Appears $value times\n";


Complete script:

Code
#!/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)


Edit Log:
Post edited by FishMonger (Veteran) on Oct 6, 2008, 2:07 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives