Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, is it appropriate to use map in void context instead of a foreach loop?

Tags:

foreach

map

perl

In Perl, if you have a loop like this:

foreach (@items) {
    perform_action($_);
}

you can replace it with a call to map in void context:

map {
    perform_action($_)
} @items;

Are there any advantages or disadvantages to doing to? Does it have a performance impact because Perl thinks it has to save the results? Does it improve/worsen readability?

like image 964
Ryan C. Thompson Avatar asked Nov 13 '10 20:11

Ryan C. Thompson


3 Answers

Starting from Perl 5.8.1 map in void context is not expensive:

map in void context is no longer expensive. map is now context aware, and will not construct a list if called in void context.

But the postfix form of for may be more readable:

perform_action($_) for @items;
like image 153
Eugene Yarmash Avatar answered Nov 09 '22 02:11

Eugene Yarmash


The problem with using map or grep in void context is mainly conceptual. Both are constructs whose job is to return a list. To discard that list makes for muddled code, unclear on the concept of listops. I never use either of those in void context myself.

I feel the same way about the ternary conditional operator. Its job is to return a value, so using it in void context makes no sense and just confuses people.

That said, I wouldn’t put too much stock into Perl::Critic or even PBP. I guess it’s better that the book exists than that it doesn’t, but people too often misunderstand the whole point and end up using it as a bludgeon.

like image 21
tchrist Avatar answered Nov 09 '22 03:11

tchrist


I believe 'Perl Best Practices' would recommend using an explicit variable in the foreach loop as the best style - it is certainly what I'd use.

foreach my $item (@items)
{
    perform_action($item);
}

It is an abuse of map (or grep) to use it in a void context.

like image 3
Jonathan Leffler Avatar answered Nov 09 '22 03:11

Jonathan Leffler