in reply to Re^3: Creating a hash from arrays
in thread Creating a hash from arrays

This is what I was doing (copied from another site):
my ($i, $j); foreach my $value (sort {$statefinal{$i} cmp $statefinal{$j}} keys %st +atefinal) { print "$value $statefinal{$value}\n"; }

That code was suppose to sort by values, but I'm just getting a lot of uninitialized values errors when I run it. It's not sorting by values (states).

Replies are listed 'Best First'.
Re^5: Creating a hash from arrays
by AnomalousMonk (Archbishop) on Nov 02, 2013 at 23:30 UTC

    $i and $j have no meaning (Update: and are given no value; i.e., are uninitialized) in your comparison expression (see sort). Try something like:

    foreach my $fn_ln (sort { $statefinal{$a} cmp $statefinal{$b} } keys % +statefinal) { print qq{'$fn_ln' in $statefinal{$fn_ln}}; }

    Update: NB: This sorts the keys (first/last name) by their values (states) in lexic-ascending order.

Re^5: Creating a hash from arrays
by LanX (Saint) on Nov 02, 2013 at 23:32 UTC
    You're using $value as key?

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re^5: Creating a hash from arrays
by tangent (Parson) on Nov 03, 2013 at 16:53 UTC
    That code was suppose to sort by values
    You're nearly there...
    my %hash; for my $i (0 .. $#fname) { $hash{ "$fname[$i] $lname[$i]" } = $state[$i] } # sort the keys by value for my $key ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) { print "$key $hash{$key}\n"; } # alternatively my @sorted = sort { $hash{$a} cmp $hash{$b} } keys %hash; for my $key ( @sorted ) { print "$key $hash{$key}\n"; }
    $a and $b are special variables and are not the same as $i and $j in your example... see sort