good chemistry is complicated,and a little bit messy -LW PerlMonks

### Problem with HOA.

by tamaguchi (Pilgrim)
 on Aug 28, 2006 at 07:03 UTC Need Help??
tamaguchi has asked for the wisdom of the Perl Monks concerning the following question:

Suppose you have following data stucture:
```my %hash=(
1=> [1.5, 2.1, 3.1],
2=> [1.2, 2.2, 3.2],
3=> [1.3, 2.3, 3.3],
)
How would you do in the easiest way to get out an array consisting of the first ellement in each of the internal valuearrays sorted by the keys? I.e. \$array[0]=1.5,  \$array[1]=1.2 and \$array[2]=1.3. Thank you fellow monk.

Replies are listed 'Best First'.
Re: Problem with HOA.
by cog (Parson) on Aug 28, 2006 at 07:10 UTC
my @array = map { \$hash{\$_}->[0] } sort { \$a <=> \$b } keys %hash;

That's the first solution that comes to my mind. Try reading it backwards:

1. Take the keys of the hash... (keys %hash)
2. ...sort them numerically... (sort { \$a <=> \$b } ...)
3. ...and get the first element of the array corresponding to each key in the hash... (map { \$hash{\$_}->[0] } ...)
Re: Problem with HOA.
by GrandFather (Sage) on Aug 28, 2006 at 07:13 UTC

Update wrong answer. cog has it right.

```use strict;
use warnings;

my %hash=(
1=> [1.5, 2.1, 3.1],
2=> [1.2, 2.2, 3.2],
3=> [1.3, 2.3, 3.3],
);

my @array = sort {\$a<=> \$b} map {@{\$hash{\$_}}} keys %hash;

print "@array";

Prints:

```1.2 1.3 1.5 2.1 2.2 2.3 3.1 3.2 3.3

DWIM is Perl's answer to Gödel

Create A New User
Node Status?
node history
Node Type: perlquestion [id://569938]
Approved by GrandFather
help
Chatterbox?
 [1nickt]: The best way is to scope it tightly so it just goes away when you are finished with it. [perldigious]: but... but... perldigious is the unvirtuous kind of lazy in this case. :-) [perldigious]: Just kidding. Thanks 1nickt, I'll go ahead and do it the right way. An extra set of brackets and a little extra indentation isn't too much to ask. [karlgoethebier]: perldigious: perhaps a block if you are paranoid ;-) [choroba]: but undef %hash and %hash = () both work, too, but the first one keeps the memory allocated, while the latter makes it available for other parts of the program. [choroba]: iirc [perldigious]: karlgoethebier: Well it is a pretty old and complicated (for me) bit of code I wrote (poorly by my current standards), so I'm expecting everything to break when I add the scoping and find out what else is undesireably scope changed. :-)

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2017-07-21 19:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (335 votes). Check out past polls.