in reply to Extracting elements from array
As many here have shown, map is a great (and probably the best) way to get what you are looking for... It is a handy tool, but, it can be a little on the arcane side if you are not used to it. Another option is foreach. If map makes your brain hurt (it does mine sometimes), foreach may be your answer. I use it most often for looping over lists (arrays/hashes/refs of both, etc...). And, if you use labels, you get some pretty easy loop control. Here is the example foreach:
my @new_array; ELEMENT: foreach my $href (@{$aref}) { push @new_array, $href if (exists $href->{name}); }
Yes, it seems like more coding than map, and it is... But, it tends to be ultra readable and really obvious about what it is doing. And like @1nickt, I sometimes lean to the more obvious coding approach, so the next poor coder to come along in 6 months does not have to spend the weekend trying to reverse engineer my cleverness (btw, that poor coder is usually me).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Extracting elements from array
by GrandFather (Saint) on Jan 15, 2016 at 19:38 UTC | |
by 1nickt (Canon) on Jan 15, 2016 at 20:24 UTC | |
by GrandFather (Saint) on Jan 15, 2016 at 21:13 UTC | |
by 1nickt (Canon) on Jan 15, 2016 at 22:05 UTC | |
by u65 (Chaplain) on Jan 16, 2016 at 11:24 UTC |