Luis Campos de Carvalho wrote:

Hy list =-]


Straight to the point:

I have a map like this:

@array = map {

     if( $something ){
       # stop, return a scalar from this block.
     }

     if( $other_thing ){
       # stop, return an array if we reach this point.
     }

# return an scalar from here.

} @process_this_things;

I need to know how I should return values from a map block at a given point. Obvious, perl prevents me from using "return" inside a map block.

So why not use a sub instead? Then you can return to your hearts content.


sub doit {
    local $_ = $_;
    return if $something;
    return if $other_thing;
    return 1;
}
@array = map(doit, @process_this_things);

You might get into slight trouble this way if $something and $other_thing have limited scope. In that case, use a closure:

my $transform = sub {
    local $_ = $_;
    return if $something;
    return if $other_thing;
    return 1;
};
@array = map { $transform->() } @process_this_things;

I know that other people have already answered this question, but I hate having more than one line in a map or grep call. So there. :-)

-Dom



Reply via email to