http://www.perlmonks.org?node_id=993506


in reply to Re: hash to count words
in thread hash to count words

So here is what i have for code so far for the hash.

#!/usr/bin/perl -w open (IN, $file) or die "Cannot open file '$file' : $!\n; $line = <IN>; @array = split ( ' ', $line); foreach $word (@array){ $word =~ s/^\w\w//g; $word = lc ($word); print "$word\n";} $hash {$the}++; $hash {$linux}++; $hash {$hello}++;
What am I doing wrong?

Replies are listed 'Best First'.
Re^3: hash to count words
by NetWallah (Canon) on Sep 13, 2012 at 15:46 UTC
    Ok - I'll take a stab at answering your question "What am I doing wrong?" :
    • Not using 'strict'. (add "use strict;" to the top of your code)
    • Not using canonical "open" with local filehandle. (Try : open(my $f, "<", $file) or die "Cannot open '$file':$!";)
    • Not declaring variables (use my @array; (follows from "use strict"))
    • Not formatting/aligning your code for visibility
    • Not following advice (davido's code works for what you need)
    • Not reading how hashes work
    • Not closing the file handle you opened.
    • Not posing your question(s) clearly
    • Not showing what you expect as a result of your code
    • Not showing sample data
    The answer to the question in your previous post on the meaning of "/g" can be found by running "perldoc perlre".

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

      Please allow an addition to the list: Not bothering to fix a previous post known to be problematic.

        Now that I have that under control, how do I print the output of the script to a file? I cannot figure it out. Thanks in advance and of course here is my coding.
        #!/usr/bin/perl -w foreach $file (@ARGV) { open (IN, $file) or die "Cannot open file '$file' : $!\n"; while(<>) { $line = <IN>; @array = split (' ', $line); foreach $word (@array){ $word =~ s/[^\w\s]//g; $word = lc ($word); $wordcount{$word} += 1; } } foreach $key (keys %wordcount) { print "Word: $key " . ($wordcount{$key}) . "\n"; } } print ("scriptOutput\n\n");