How can I return a list of hashrefs from a map in Perl?

dictionary, list, perl

Solution

It only gives a syntax error because you Perl thinks you need to omit the comma after `map { ... }`, because it is parsing that map as being a block, not an expression. Putting `+` in front will fix that. Also, you can't have a semicolon in an anonymous hash:

my $results = { data => [
   map +{
#      ^----------------- plus sign added
      %{$_->TO_JSON},
      display_field => $_->display_field($q);
#                                           ^---- should be comma or nothing
   }, $rs->all
]};

Problem

I have the following mostly ok code: ``` my $results = { data => [ map { my $f = $_->TO_JSON; $f->{display_field} = $_->display_field($q); $f; } $rs->all ]}; ``` Only I'd rather it were more like the following: ``` my $results = { data => [ map { %{$_->TO_JSON}, display_field => $_->display_field($q), }, $rs->all ]}; ``` But that gives a syntax error. How can I do what I want, or is my current version the best it gets? update: sorry about the extra semicolon from before. It's late here. Not sure how I missed it. Thanks guys!

Original source