hotshot has asked for the wisdom of the Perl Monks concerning the following question:

hello my friends!

I have the following function for sorting hash by it's values:
sub sortHash { my $hash = shift; my @keys = sort { @a = split(/[,-]/, $hash->{$a}); @b = split(/[,-]/, $hash->{$b}); $a[0] cmp $b[0] || $a[1] <=> $b[1] } keys(%{$hash}); return \@keys; }
the functions works for hashes like:
my %hash = ( '2.2.2.2' => 'nfs,1', '6.6.6.6' => 'afp-0', '3.3.3.3' => 'nfs-0', '4.4.4.4' => 'cifs,1', '1.1.1.1' => 'cifs,0', );
the function return the keys sorted by the values, for the above hash it will return:
my $array = &sortHash(\%hash); print Dumper($array); # will print $VAR = [ '6.6.6.6', '1.1.1.1', '4.4.4.4', '3.3.3.3', '2.2.2.2', ];
The problem is that the values in the hash not always contain the index, and I get an use of Uninitialize value in numeric ....
Is there a way to chech for existence somehow in the sort function?

Hotshot

Replies are listed 'Best First'.
Re: sort by hash with existence check
by fruiture (Curate) on Nov 13, 2002 at 11:17 UTC

    First, you really want to use Schwartzian Transform and of course you can check for existence, in this case you check for defined()ness and you must specify the behaviuor: is 'nis-1' greater than 'nis' or less than or what? I assume 'nis-1' and 'nis' must be equal

    sub sortHash { my $hash = shift; [ map { $_->[0] } sort { $a->[1] cmp $b->[1] or defined( $a->[2] ) and defined( $b->[2] ) and $a->[2] <=> $b->[2] } map { [ $_ , split /[-,]/ ] } keys %$hash ] }
    --
    http://fruiture.de
Re: sort by hash with existence check
by jdporter (Paladin) on Nov 14, 2002 at 05:33 UTC