Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Transferring hash keys to array... Need help sorting

by huck (Prior)
on Apr 21, 2017 at 02:53 UTC ( [id://1188506]=note: print w/replies, xml ) Need Help??


in reply to Transferring hash keys to array... Need help sorting

I just bet that my @labels = sort keys %hash worked just fine didnt it? Your problem was that when you said tried to get the contents they didnt line up. So what you want is to line up the values of @contents with the values in @labels. It would have been nice if you showed us what you did try, but at one point i expect you had something like

my @labels; my @content; for my $var (keys(%hash)){ push @labels,$var; push @content,$hash{$var}; }
and that was when you were complaining they were random.

so what if i mentioned that keys %hash looks like an array. in fact you could have said my @arr=keys(%hash); for my $var(@arr) { ... }. And you have seen that sort in fact does sort character values like you want. so what if you said my @arr=keys sort(%hash); for my $var(@arr) { ... } what do you think would happen?. So lets go a step farther, keys looks like an array, sort takes an array and looks like an array. we could just double things up, for my $var(sort(keys(@arr)))  { ... }

Replies are listed 'Best First'.
Re^2: Transferring hash keys to array... Need help sorting
by DARK SCIENTIST (Novice) on Apr 21, 2017 at 03:10 UTC
    So what you're suggesting is that the arrays are being sorted correctly, but just not aligned with one another? That makes sense so I could adjust accordingly per your advice here... See I thought the problem might have been that I wanted to sort the keys (labels) according to the integer following "label" and that because I was using character sorting that's why it wasn't working. Or is that not the case?

      Well thats another kettle of fish. you want to sort by contents and leep labels in synced order. This will sort labels by the contents of $hash numerically <=>.

      my @labels=sort {$hash{$a}<=>$hash{$b}} keys %hash; my @content = @hash{@labels};

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-24 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found