Alex Rivera | Logout

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

Asked 2010-11-13T20:20:03.827
12

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?

Edit
Report

1 Answer

18

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;
answered 2010-11-13T20:29:05.180

Your Answer