in reply to 'Simple' comparing a hash with an array
#!/usr/bin/perl use strict; use warnings; my %histogram = map { $_ => 0 } qw( a am an and are as at be been but by can co de do due each ); # hash of the words to find so we can do an O(1) lookup for them while ( <> ) { chomp; for ( split ) { # split returns a list we can use directly $histogram{ $_ }++ if exists $histogram{ $_ }; # only store counts for words that matter } } foreach my $word ( keys %histogram ) { # keys() will list the keys, and we've already taken care # of making sure we don't have extra words stored. # Now there's no need to do two loops and check an array # against a hash. print "Found $word, $histogram{$word} times.\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 'Simple' comparing a hash with an array
by Anonymous Monk on Apr 17, 2008 at 14:16 UTC | |
by mr_mischief (Monsignor) on Apr 17, 2008 at 15:28 UTC | |
|
Re^2: 'Simple' comparing a hash with an array
by wade (Pilgrim) on Apr 17, 2008 at 16:23 UTC |