Rodster001 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings!

I want to do this in one line but I am having trouble coming up with a solution. $v is an array ref of hashes and each hash in the array has a "name" element and I want to create a string joining that value.

Something like:

my $res = join(",",@{$v}->{name}); # not working
I am able to reference a value of name specifically doing this:
my $name = ${$v}[0]->{name};
So I am not quite sure why my join above is not working. Can this be done in one line? Please enlighten me, thanks!

Replies are listed 'Best First'.
Re: Joining an array of hashes
by kyle (Abbot) on Dec 11, 2008 at 18:43 UTC

    Use map for this.

    my $res = join q{,}, map { $_->{name} } @{ $v };
Re: Joining an array of hashes
by jeffa (Bishop) on Dec 11, 2008 at 18:37 UTC

    You were *this* close:

    my $res = join(",",@{ $v->{name} });

    Update: I think kyle is correct. I should have asked to see what the dump of @v is.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Yeah, Kyle's suggestion was correct. Map worked great.

      Thanks! Just FYI here is Dumper($v) output

      $VAR1 = [, {, 'name' => 'Cat', 'id' => '7670', }, {, 'name' => 'Dog', 'id' => '7671', }, ];, $VAR1 = [, {, 'name' => 'Cat', 'id' => '7670', }, ];,