Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like `last` for `map`?

Tags:

perl

In Perl, is it possible to arbitrarily end a map execution, e.g. something equivalent to last in a loop?

It would be a bit like this:

map {
    if (test == true) { last; } dosomething
} @myarray
like image 978
benzebuth Avatar asked Aug 26 '10 13:08

benzebuth


1 Answers

Nope. You can't last, next, etc. out of a map, grep or sort blocks because they are not loops.

Having said that, the code snippet in the question is poor practice because map should never be called in void context. They are supposed to be used to transform one list into another.

Here's a better way to write it if you really must inline it (modified after ysth's comment):

 $_ == 10 && last, print for 1..15;  # prints '123456789'
like image 119
Zaid Avatar answered Oct 06 '22 00:10

Zaid