Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Creating a hash from arrays

by AnomalousMonk (Archbishop)
on Nov 02, 2013 at 22:42 UTC ( [id://1060987]=note: print w/replies, xml ) Need Help??


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

How are you calling sort on values?

Replies are listed 'Best First'.
Re^4: Creating a hash from arrays
by cspctec (Sexton) on Nov 02, 2013 at 22:56 UTC
    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).

      $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.

      You're using $value as key?

      Cheers Rolf

      ( addicted to the Perl Programming Language)

      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1060987]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-19 19:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found