in reply to Re^2: Sorting hashes with new value detection
in thread Sorting hashes with new value detection
Something like this perhaps?
use warnings; use strict; my %lookup = ( a => 2, b => 4, c => 4, d => 4, e => 1, f => 5, g => 6, h => 3, i => 2, j => 7, k => 7, l => 4, m => 3, n => 3, o => 2, p => 5, q => 11, r => 5, s => 3, t => 3, u => 2, v => 4, w => 7, x => 10, y => 7, z => 9 ); my @scores; while ( my $line = <DATA> ) { chomp $line; my @words = split /\s+/, $line; for my $word (@words) { $word =~ s/[^A-Za-z]//g; next unless length $word; my @letters = split //, $word; my $score; $score += $lookup{ lc $_ } for @letters; push @{ $scores[$score] }, $word; } } for my $score ( 0 .. $#scores ) { if ( defined @{ $scores[$score] } ) { my %words; @words{ @{ $scores[$score] } } = undef; print 'Scored ', $score, ":\n"; print " $_\n" for sort { length $a <=> length $b || $a cmp $b } keys %words; print "\n"; } } __DATA__ In short, I am creating a little word game Each character is worth X points, so I record the word in the hash along with the value of the entire word. That's what the numbers are in the example (not accurate, mind you, it's just basic sample code). When I print out scores, I'll need to be able to sort by the length of the word and/or sort by the word values. When sorted by value, I need to be able to display all words in specific categories by their value. All 5 pt words are grouped together, as so on.
|
|---|