<?xml version="1.0" encoding="windows-1252"?>
<node id="1013574" title="How does 'goto LABEL' search for its label?" created="2013-01-16 08:50:50" updated="2013-01-16 08:50:50">
<type id="115">
perlquestion</type>
<author id="616540">
moritz</author>
<data>
<field name="doctext">
&lt;p&gt;At $dayjob I'm working on a project where the home-grown error reporting module occasionally warns &lt;c&gt;Use of "goto" to jump into a construct is deprecated&lt;/c&gt;

&lt;p&gt;So now I'm trying to find out how exactly [doc://goto] LABEL works, in order to assess whether the whole error reporting module needs to be rewritten. And I found no documentation.

&lt;p&gt;The closest I found was [id://508852|"goto only searches the immediate call stack for labels"], but this alone doesn't explain how "jump into a construct" can happen at all -- if it only searched the caller's scope and the caller's caller's scope etc. for the label, it would never find label from inside a construct that's not in dyanmic call chain.

&lt;p&gt;Some curious experiments:

&lt;code&gt;
$ perl -wE 'if (0) { label: say 1 }; goto label'
Can't find label label at -e line 1.
$ perl -wE 'if (1) { label: say 1;}; goto label' 
Use of "goto" to jump into a construct is deprecated at -e line 1.
1
Use of "goto" to jump into a construct is deprecated at -e line 1.
1
^C # aborted, because it loops
&lt;/code&gt;

&lt;p&gt;So apparently, the construct containing the label has to have been executed once.

&lt;p&gt;This works:

&lt;code&gt;

#!/usr/bin/perl
use strict;
use warnings;
use 5.014;

sub f {
    my $arg = shift;
    if ($arg == 0) {
        label:
        say 'here';
    }
    elsif ($arg == 1) {
        # don't execute a branch with 'label:'
    }
    else {
        goto label
    }
}
f($_) for 0..2;
__END__
here
here
&lt;/code&gt;

&lt;p&gt;Whereas this one dies:

&lt;code&gt;
$ perl -wE 'sub g() { label: say "here" }; g; goto label'
here
Can't find label label at -e line 1.
&lt;/code&gt;

&lt;p&gt;I have trouble finding a clear mental model that can help me to explain all of this behavior. Who can help?&lt;/p&gt;


&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-616540"&gt;
[http://perl6.org/|Perl 6 - the future is here, just unevenly distributed]
&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
