in reply to Make CSV list from values in AoH

Another way. Distinguishes undefined from non-existent keys (may be surplus to requirements). Needs 5.10+ for the  // defined-or operator.

c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; my @AoH = ( { name => 'Adam', age => 0, }, { name => 'Bob', age => 10, }, { name => 'Cat', age => 20, }, { name => '0', age => 30, }, { name => 0, age => 35, }, { name => '', age => 40, }, { name => undef, age => 50, }, { age => 60, }, ); ;; my @empty; ;; print make_csv('name', @AoH); print make_csv('name', @empty); print make_csv('name'); print make_csv(); print make_csv('name', { name => 'Foo', age => 91, }); print make_csv('name', { name => '0', age => 92, }); print make_csv('name', { name => 0, age => 93, }); print make_csv('name', { name => '', age => 94, }); print make_csv('name', { name => undef, age => 95, }); print make_csv('name', { age => 96, }); ;; sub make_csv { my $k = shift; return qq{'@{[ join q{','}, map exists $_->{$k} ? $_->{$k} // '[UNDEF]' +: '???', @_ ]}'}; } " 'Adam','Bob','Cat','0','0','','[UNDEF]','???' '' '' '' 'Foo' '0' '0' '' '[UNDEF]' '???'


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

Replies are listed 'Best First'.
Re^2: Make CSV list from values in AoH
by tel2 (Pilgrim) on Aug 20, 2018 at 02:07 UTC
    Thanks AnomalousMonk,

    Your effort is appreciated even if it wouldn't work with 'strict' in use.

    tel2

      ... it wouldn't work with 'strict' in use.

      Whatever makes you think that? See command line invocation
          c:\@Work\Perl\monks>perl -wMstrict -le
      which enables full strictures (and also, I must admit, global warnings; not, in general, a good idea, but OK for command line examples). (Update: In general, everything I post on PerlMonks and all the code I write has lexical strictures and warnings fully enabled, with only very specific strictures/warnings lexically disabled. I consider this a Best Practice.)


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

        My humblest apologies, AnomalousMonk.

        I didn't read Tux's post carefully enough, and because it appeared under your post, I wrongly thought Tux was talking to you.  But looking now at the indentation of Tux's post, it looks as if he was responding to my original post.  I wasn't meaning to claim your code wouldn't work with 'strict', but I was trying to allow for that possibility, if what I thought Tux was saying, was correct.

        Sorry.