That doesn't have to do with scope, but with compile time and run time. Here's a simplified explanation.
The Perl interpreter will scan your code initially, and follow any use
statements or BEGIN
blocks. At that point, it sees all the sub
s, and notes them down in their respective packages. So now you have a &::myf
in your symbol table.
When compile time has reached the end of the program, it will switch into run time.
At that point, it actually runs the code. Your first print
statement is executed if &myf
is defined. We know it is, because it got set at compile time. Perl then calls that function. All is well. Now you undef
that entry in the symbol table. That occurs at run time, too.
After that, defined &myf
returns false, so it doesn't print.
You even have the second call to myf()
there in the code, but commented out. If you remove the comment, it will complain about Undefined subroutine &main::myf called. That's a good hint at what happened.
So in fact it doesn't look forward or backward in the code. It is already finished scanning the code at that time.
The different stages are explained in perlmod.
Note that there are not a lot of use cases for actually undef
ing a function. I don't see why you would remove it, unless you wanted to clean up your namespace manually.
undef
is code to run at runtime, butsub
is a definition and happens at compile time. – Kowtow