On Sun, 10 Jun 2001, Charles Lu wrote:
> Variable "%hash" will not stay shared....
I forgot to mention a few little details.. so here is your example
code with the corrections to get rid of the unsharing problem.
use strict;
my @list = ('apple',12, 'peach', 2, 'pear', 45);
&function_one(@list);
sub function_one {
my %hash = @_;
my $by_value = sub {
$hash{$a} <=> $hash{$b};
};
my @newhash = sort $by_value keys %hash;
foreach(@newhash) {
print "$_\t\t$hash{$_}\n";
}
}
Note the change to by_value. by_value is no longer a subroutine, but a
reference to a subroutine.. which is why it needs to be called as
$by_value in sort. To use it anywhere else as a subroutine you would need
to call it as &$by_value(xxx,xxx).
You could also simply use an anonymous subroutine in the sort command
itself like this...
my @newhash = sort { $hash{$a} <=> $hash{$b}; } keys %hash;
...which is a bit cleaner if you don't care or need to re-use that
subroutine elsewhere.
--
Ian