Reputation: 1218
I'd like to concatenate the output of the map
function in Perl to a string variable. However, if I try this:
$body .= map {"$_\n"} sort(@{$hash{$server}->{VALID}});
The value of $body equals 3 instead of the expected
user1 user2 user3
If I do:
print map {"$_\n"} sort(@{$hash{$server}->{VALID}});
it gives me what I want.
So how can I mimic the print map functionality and assign it to the body variable?
Upvotes: 1
Views: 849
Reputation: 5220
print
concatenates the array returned by map
, interleaving items with the value of $,
.
So, you need this to simulate print
behavior:
$body .= join $,, map {"$_\n"} sort(@{$hash{$server}->{VALID}});
As long as print
is your concern, another valid possibility is:
print "$_\n" for sort(@{$hash{$server}->{VALID}});
Or, enabling Perl v5.10 feature say
, just:
say for sort(@{$hash{$server}->{VALID}});
Extrapolating that for concatenation:
$body .= "$_\n" for sort(@{$hash{$server}->{VALID}});
Upvotes: 4
Reputation: 66998
map
is used to transform a list into another list, so that's what it returns. This works with print
because the print
function takes a list and will output them separated by the value of $,
(the output field separator.)
If you want to join a list together into a string, you have to use join
.
$body .= join "\n", sort(@{$hash{$server}->{VALID}});
Upvotes: 5