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

    However

    my @newArray = grep {exists $_->{name}} @$aref;

    seems a lot cleaner and easier to maintain than the version you offered. Is grep really that much more arcane than using if as a statement modifier, a superfluous statement label and redundant {} when dereferencing a simple array reference?

    Premature optimization is the root of all job security

      dereferencing a simple array reference

      I always dereference with curly braces, AND whitespace! Sure, it's redundant, but it allows my tired old eyes to see what I just wrote.

      keys %$href
      keys %{ $href }
      I have to squint a little to read the former; not so much on this page, but on the terminal, definitely. :-( But to each their own, eh?

      The way forward always starts with a minimal test.

        When you read English prose like :

        He (Tom) ...

        where do you expect to see white space ? Why should your expectations be different for other languages ( even artificial ones ) ?

        You have been trained since your first exposure to printed English to very standardised use of white space . Are you suggesting we should throw away all that hard wired preprocessing and reinvent a whole ' nother wheel ? Have you even tried typing prose with " silly " white space ? It ' s actually quite slow because it ' s not at all " natural ". What ' s it like to read ? Do ( ( redundant ) ) or ( unnecessary ) brackets help ?

        Premature optimization is the root of all job security