Hi Todd,
Stick your code that you've defined into a Perl subroutine that takes in a hash. Then you can call that subroutine each time you want to perform your algorithm. By the way, you don't need to define the byValue subroutine. Perl lets you use an anynomous subroutine right in the sort statement.
The syntax of using the anynomous subroutine in the sort operation is:
sort BLOCK LIST
I took your code and put it into a subroutine that I called hash_value_sort and then I just called it on each hash instance I had. The subroutine just took in the hashes and worked with them. A Perl subroutine will take a list of scalars or a single hash. If you need to pass in something more complex -- multiple lists, multiple hashes, objects, etc. -- you can pass in references, a reference is just a scalar whose value is a reference. So you can pass in two lists or two hashes or whatever by passing in a reference to each thing. However, in your example you're only working with one thing and your not trying to modify it, so you don't need to pass in a reference, although if it were very big, you might want to since it would be much faster (in Perl a reference is like a pointer in C).
Sticking the code you want to use over again into a subroutine that takes in a hash causes your hashes to get copies into that local hash in the subroutine you've written each time it's called. That local hash copy in the subroutine gets defined by using my, not by using local, which may seem confusing.
Here's the code, hope it helps.
#!perl
use strict;
&main();
sub main {
my %hash1 = ( "george" => "salsa",
"doug" => "apple",
"steve" => "cantaloupe",
"alex" => "blueberry",
"andrew" => "ginger" );
my %hash2 = ( "william" => "cats",
"robert" => "dogs",
"randy" => "birds",
"phillip" => "fish" );
my %hash3 = ( "amy" => "swims",
"georgianne" => "runs",
"susan" => "jogs",
"stephanie" => "walks",
"sarah" => "bicycles",
"debbie" => "dances" );
print "The result of calling hash_value_sort on \%hash1 is\n";
&hash_value_sort( %hash1 );
print "\n";
print "The result of calling hash_value_sort on \%hash2 is\n";
&hash_value_sort( %hash2 );
print "\n";
print "The result of calling hash_value_sort on \%hash3 is\n";
&hash_value_sort( %hash3 );
print "\n";
my @keys_sorted_by_value1 = &get_sorted_keys( %hash1 );
my @keys_sorted_by_value2 = &get_sorted_keys( %hash2 );
my @keys_sorted_by_value3 = &get_sorted_keys( %hash3 );
print ( "The keys of \%hash1 sorted by their values are: ", ( join
+( ", ", @keys_sorted_by_value1 ) ), "\n" );
print ( "The keys of \%hash2 sorted by their values are: ", ( join
+( ", ", @keys_sorted_by_value2 ) ), "\n" );
print ( "The keys of \%hash3 sorted by their values are: ", ( join
+( ", ", @keys_sorted_by_value3 ) ), "\n" );
print "\n";
return;
}
sub hash_value_sort {
my %h = ( @_ );
my $key;
foreach $key ( sort { $h{$a} cmp $h{$b} } keys %h ) {
print "$key - $h{$key}\n";
}
return;
}
sub get_sorted_keys {
my %h = ( @_ );
return sort { $h{$a} cmp $h{$b} } keys %h;
}
|