[Melbourne-pm] Nested maps returning hash references
Myf White
myfwhite at gmail.com
Wed Oct 5 00:24:24 PDT 2011
On Wed, Oct 5, 2011 at 5:42 PM, Toby Corkindale <
toby.corkindale at strategicdata.com.au> wrote:
> On 05/10/11 17:34, Alfie John wrote:
>
>> Hey Toby,
>>
>> I think there are two problems here:
>>
>> - Andrew was right. Put a + in front of the block
>> - can($_) in the second block is being called on the qw{} and not on
>> an object
>>
>
> In case people want working test code, here is some below.
> By the way, I was trying to put the + on line 11 below, to no success, but
> perhaps you mean a different {?
> (I'm picking the, umm, third that occurs in the whole program, or second
> within the map..)
>
>
> #!/usr/bin/env perl
> use 5.14.1;
> use warnings;
> use Data::Dumper;
>
> my @fields = map { Foo->new($_) } qw(bing bang bong);
>
> my $foo = [
>
> map {
> my $f = $_;
> {
> map {
> $f->can($_) ? ($_ => $f->$_) : ()
> } qw(label name html);
> }
> } @fields
> ];
>
> say Dumper($foo);
>
> package Foo;
>
> sub label { shift->{label} }
>
> sub new { bless { label => $_[1] } }
>
> 1;
>
>
On 5.10.1 that didn't work for me. I tried it with adding a local variable
for the hashref inside the first map, which seemed to do what I think you're
trying to do
my $array_ref = [map {
my $f = $_;
my $inner = {
map {
$f->can($_) ? ( $_ => $f->$_ ) : ();
} qw/label name html/
};
$inner;
} @fields];
I would be careful putting subroutine calls inside maps that are being used
for hashes though, because the returns from $f->label, $f->name, $f->html
can only ever be a single value. If someone decides to change what gets
returned, you could end up with "odd number of elements" errors. I do it
pretty commonly, but only if I'm confident the testing around it is decent.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20111005/e6a5c7c5/attachment.html>
More information about the Melbourne-pm
mailing list