Perl hash example
Jump to navigation
Jump to search
Perl: hash example
The contents of this page has recently been imported from an older version of this Wiki. This page may contain outdated information, information that is irrelevant for this Wiki, information that needs to be differently structured, outdated syntax, and/or broken links. Use with caution!
An example of using a hash in Perl and sorting over its values.
Contents
Please download The Raven for this example. Save this file somewhere on your hard disk.
Start Komodo, then copy the code below and save it. Then run the code. In the Debugging Options window, enter the path and filename to TheRaven.txt into the filed for Script Arguments. This line contains what you would normally type on the commandline, i.e. the arguments taht get stored in the global variable @ARGV (the argument vector).
#!/usr/bin/perl
use strict;
use warnings;
my $filename = shift(@ARGV);
my @tokens;
my %dictionary;
open (INFILE,"< $filename") or die("Failed to open $filename: $!");
while (my $line = <INFILE>) {
$line = lc($line);
$line =~ s/^[^a-z]+//;
@tokens = split(/[^a-z]+/,$line);
foreach my $word (@tokens) {
$dictionary{$word}++;
}
}
close(INFILE);
my @keys = keys(%dictionary);
my @value_sorted_keys = sort {$dictionary{$a}<=>$dictionary{$b}} (@keys);
foreach my $word (@value_sorted_keys) {
print "$dictionary{$word} $word\n";
}
exit();
Analyse this code line by line.
Further reading and resources