http://www.perlmonks.org?node_id=1013695


in reply to How does 'goto LABEL' search for its label?

I believe it is a rather simple search up the call stack. And all of your examples agree with that. Don't confuse that with searching up a "stack" of nested (or even prior) lexical blocks.

A 'goto' is visible inside of the bounds of the dynamic scope where it lives. The two things that most clearly define a dynamic scope are: sub, eval. This certainly includes the subs that you can define without using the 'sub' keyword by passing a block to a sub with a prototype that starts with a '&' character. It is less clear how similar the separation is for similar scopes that can be built in a lot of places in Perl, including: map, grep, s///e, sort.

So apparently, the construct containing the label has to have been executed once.

Not true. The construct just mustn't be optimized away as happens when you give an 'if' statement an expression that is known to be false at compile time.

$ perl -wE 'sub g() { label: say "here" }; g; goto label' here Can't find label label at -e line 1.

Of course. g() has already returned by the time you execute "goto label", so the contents of g()'s dynamic scope are not present further up the call stack, so Perl can't find the "label:".

As for there being a new warning for "if(1){X:...} goto X:", I lack the details for why this got deprecated. It seems to go rather farther than any prior restrictions and seems likely to run afoul of rather typical "use of 'goto' for error handling" that I've seen (though not frequently):

... if( ... ) { goto ERR; } ... if( $fatal ) { ERR: ... clean up after fatal error ... }

- tye