First of all, do not comment out 'use strict' and 'use warnings'. If you have to ask why, you aren't to a level where you should consider doing so.
Second, you have a ',' (comma) at the end of your assignment to $file_name where you should have a ';' (semicolon), which is an error (that you would have found using 'strict' and 'warnings'). Once this was fixed, the code you provided (with the line '..' commented out) generated the expected output.
Tested code:
$ cat 11104497.pl
#!usr/bin/local/perl
use strict;
use warnings;
my %count;
my $file_name = shift or die "Usage: perl $0 [FILE]\n";
open my $fh, '<', $file_name or die "Could not open '$file_name' $!";
while ( my $line = <$fh> ) {
chomp $line;
foreach my $word ( split /\s+/, $line ) {
$count{$word}++;
}
}
foreach my $word ( sort keys %count ) {
printf "%-31s %s\n", $word, $count{$word};
}
# ..
my @sorted_by_count = sort { $count{$b} <=> $count{$a} } keys %count;
print "These are the 10 most frequented words of $file_name :\n";
print "$_ occured $count{$_} times\n" for @sorted_by_count[ 0 .. 9 ];
Output:
$ cat janne.txt
This is a test.
This is only a test.
Had this been an actual emergency, the attention signal you just heard
+ would have been followed by news or instructions.
This has been a test.
$
$ perl 11104497.pl janne.txt
Had 1
This 3
a 3
actual 1
an 1
attention 1
been 3
by 1
emergency, 1
followed 1
has 1
have 1
heard 1
instructions. 1
is 2
just 1
news 1
only 1
or 1
signal 1
test. 3
the 1
this 1
would 1
you 1
These are the 10 most frequented words of janne.txt :
a occured 3 times
This occured 3 times
been occured 3 times
test. occured 3 times
is occured 2 times
has occured 1 times
or occured 1 times
news occured 1 times
by occured 1 times
this occured 1 times
$
Moral of the story: when in doubt, use 'use strict' and 'use warnings'.
Hope that helps.
2019-09-14: Removed duplicated 'and's and added missing 'the' to paragraph two (2), sentence two (2).
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|