in reply to Basic help with mapping
map generally returns a list, not an array ref. Here, you're calling it in scalar context, so it actually returns the number of items in its return list. This isn't what you want, judging by your variable names.my $AoH_new = map ...
For each item in the list, map executes the block with that item aliased to $_. But here you are treating $_ as an array index for @$AoH_orig, not as an element of $AoH_orig. Either map over the actual indices (0 .. $#$AoH_orig), or use something closer to your second example, which is:my $AoH_new = map { $AoH_orig->[$_]{'title'} =~ s/ /_/g } @$AoH_orig;
Each time map executes the block, it accumulates the return value of the block in a list, and finally returns the list. In this case, you're accumulating the return values of "$str =~ s///g" statements. But these statements only return the number of changes made to the string. Again, it seems like you want modified copies of the strings in $AoH_orig, with a similar structure -- not a list of the number of changes made to each string.my $AoH_new = map { $_->{'title'} =~ s/ /_/g } @$AoH_orig;
Or even better, perhaps:my @AoH_new = map { ## store the result in an array my %h = %$_; ## make a copy of each hashref $h{title} =~ s/ /_/g; ## modify a value in the hash copy \%h; ## return a ref to that copy } @$AoH_orig;
use Storable 'dclone'; my $AoH_new = dclone $AoH_old; ## copy the old structure ## change an item in each hash in the new copy $_->{title} =~ s/ /_/g for @$AoH_new;
Update: changed "$h->" to "$h" in my example. Thanks Errto.
blokhead
|
|---|