in reply to A useful use of goto

{ no strict 'refs'; # We don't want to introduce another scope, as that will # negate the effect of the local: NEXT: my $n = shift @handlers; local *{$n} = $handler{ $n }; goto NEXT if @handlers; $ok = eval $cfg_str; $err = $@; }

The code is inside a loop (yes it is) so there is no need to use goto:

NEXT: { no strict 'refs'; # We don't want to introduce another scope, as that will # negate the effect of the local: my $n = shift @handlers; local *{$n} = $handler{ $n }; redo NEXT if @handlers; $ok = eval $cfg_str; $err = $@; }

Or perhaps:

{ no strict 'refs'; # We don't want to introduce another scope, as that will # negate the effect of the local: NEXT: { my $n = shift @handlers; local *{$n} = $handler{ $n }; redo NEXT if @handlers; } $ok = eval $cfg_str; $err = $@; }

Replies are listed 'Best First'.
Re^2: A useful use of goto
by Corion (Patriarch) on Apr 11, 2010 at 21:55 UTC

    Ah yes, I forgot about redo. But your second approach introduces another block and thus won't work:

    my %handler = ( hello => sub() { print "hello world\n" }, ); my ($ok,$err); my @handlers = keys %handler; my $cfg_str = 'hello();'; { no strict 'refs'; # We don't want to introduce another scope, as that will # negate the effect of the local: NEXT: { my $n = shift @handlers; local *{$n} = $handler{ $n }; redo NEXT if @handlers; } $ok = eval $cfg_str; $err = $@; } warn $err if $err; __END__ Undefined subroutine &main::hello called at (eval 1) line 1.
Re^2: A useful use of goto
by The Perlman (Scribe) on Apr 11, 2010 at 22:06 UTC
    > The code is inside a loop (yes it is) so there is no need to use goto:

    Are you sure? IMHO each redo means leaving the scope and "delocalizes" all variables so far.

    perl -e ' NEXT: { local $a.=$x++; redo NEXT if $x<10; print $a; # prints only 9 } '
    BTW: no need for a NEXT label, redo alone would do! : )

    UPDATE: I think you're wrong!

    $x=0; { NEXT: { $x==0 ? (local $a="A") : (local $b="B"); redo NEXT if $x++<1; print $a,$b; } }
    only prints "B"! BUT
    $x=0; { NEXT: $x==0 ? (local $a="A") : (local $b="B"); goto NEXT if $x++<1; print $a,$b; }
    prints "AB"
Re^2: A useful use of goto
by The Perlman (Scribe) on Apr 11, 2010 at 21:54 UTC
    > Or perhaps:

    nope, shouldn't work, each block in perl has its own scope.