How to extract a value from all the hashes in a list of hashes?

M

mrstevegross

I have a list of hashes that looks like this:

my @list = (
{ Name => 'Foo', X => Y },
{ Name => 'Bar', X => Y },
{ Name => 'Baz', X => Y },
);

I would like to iterate across the list-of-hashes and extract just the
values of the 'Name' key as a list. I had hoped that the following
code would do the trick:

my @names = grep { $_->{Name} } @list;

But it doesn't, because the grep simply matches the hash reference but
doesn't return the value of the named attribute. Is there a quick way
to make this work, other than iterating across the list with a
foreach() statement?

Thanks,
--Steve
 
J

Jürgen Exner

mrstevegross said:
I have a list of hashes that looks like this:

my @list = (
{ Name => 'Foo', X => Y },
{ Name => 'Bar', X => Y },
{ Name => 'Baz', X => Y },
);

I would like to iterate across the list-of-hashes and extract just the
values of the 'Name' key as a list. I had hoped that the following
code would do the trick:

my @names = grep { $_->{Name} } @list;

But it doesn't, because the grep simply matches the hash reference but
doesn't return the value of the named attribute. Is there a quick way
to make this work, other than iterating across the list with a
foreach() statement?

my @names = map $_ -> {Name}, @list;

jue
 
T

Tad J McClellan

mrstevegross said:
Thanks--it works great!


If you had paid close attention when you read the documentation
for the function you were using, you could have discovered this
on your own:

perldoc -f grep

...
See also L</map> for a list composed of the results of the BLOCK or EXPR.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top