Search code examples
loopsperl

Label cannot be used to last i.e. break for label in the front?


How come perl cannot last i.e. break for label in the front ahead ? How should the correct syntax be ?

my $f;my $err=9;
my @l=(7,8,9,10);
for (@l) { 
  last T if $_==$err
}
$f=@l;
print "\ncomplete";
T:
print "\ncontain error";

Label not found for "last T" at ./non.pl line 17 

Solution

    • return exits scopes until a sub call is found,
    • die exits scopes until an eval is found, and
    • last, next and redo exit scopes until a loop is found.

    To jump ahead, use goto.

    goto T if $_ == $err;
    

    But wouldn't this be clearer:

    my @l = ( 7, 8, 9, 10 );
    
    my $err = 9;
    
    my $f;
    if ( grep { $_ == $err } @l ) {   # Or `first` from List::Util
       say "contain error";
       $f = undef;
    } else {
       say "complete";
       $f = @l;
    }
    

    If you plan to check against the same @l many times, this would be better:

    my @l = ( 7, 8, 9, 10 );
    my %l = map { $_ => 1 } @l;
    
    my $err = 9;
    
    my $f;
    if ( $l{ $err } ) {
       say "contain error";
       $f = undef;
    } else {
       say "complete";
       $f = @l;
    }