in reply to Extracting elements from array

Without the need to "manually" step over the zeroth element (i.e., process only hash refs. that have a  'name' key):

<c> c:\@Work\Perl>perl -wMstrict -le "use Data::Dump qw(dd); ;; my $data = [ { val => 'action', acc => 'Accounts', id => 'None', }, { name => 'PA1', id => 'AUTOB' }, { name => undef, id => 'AUTOP' }, { name => '0', id => 'BOP' }, { name => 0, id => 'DFIRE' }, { name => '', id => 'HOME' }, { name => 'CM7', id => 'CUMBR' }, { name => 'BR1', id => 'PUMBR' }, { name => 'TY6', id => 'ECUST' }, ]; ;; my $k = 'name'; my $names = [ map { exists $_->{$k} ? { $k => $_->{$k} } : () } @$data ]; dd $names; " [ { name => "PA1" }, { name => undef }, { name => 0 }, { name => 0 }, { name => "" }, { name => "CM7" }, { name => "BR1" }, { name => "TY6" }, ]

Update: Changed example code to include various false values for  $k selected key.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Extracting elements from array -- grep
by Discipulus (Canon) on Jan 15, 2016 at 08:44 UTC
    When i read the title i was sure grep was the solution.. when i read all solutions used map i was surprised.

    Using grep was trickier than i thought (but is a function i started using recently (2 years or so)) was trickier 'cause of his return value accomplished using $_ = ..
    use strict; use warnings; use Data::Dump; my $aref =[ { val => 'action', acc => 'Accounts', id => 'None', }, { name => 'PA1', id => 'AUTOB' }, { name => undef, id => 'AUTOP' }, { name => '0', id => 'BOP' }, { name => 0, id => 'DFIRE' }, { name => '', id => 'HOME' }, { name => 'CM7', id => 'CUMBR' }, { name => 'BR1', id => 'PUMBR' }, { name => 'TY6', id => 'ECUST' }, ]; dd [ grep { exists $_->{name} and $_={'name' => $_->{name}} } @$aref ] +; # OUTPUT [ { name => "PA1" }, { name => undef }, { name => 0 }, { name => 0 }, { name => "" }, { name => "CM7" }, { name => "BR1" }, { name => "TY6" }, ]


    HtH
    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      [ grep { exists $_->{name} and $_={'name' => $_->{name}} } @$aref ]

      Beware that  $_={'name' => $_->{name}} clobbers  $aref because  $_ is an alias. (Of course,  $_ in map is also an alias, so it's possible to do oneself an injury with map also, but also easier to avoid. :-)


      Give a man a fish:  <%-{-{-{-<