Please take a look at the following code:
use strict;
use warnings;
print "subroutine is defined\n" if defined &myf;
myf();
sub myf
{
print "called myf\n";
}
undef &myf;
#myf();
print "now subroutine is defined\n" if defined &myf;
The output is
subroutine is defined
called myf
The first print statement can print, does that mean the interpreter (or compiler?) looks further and sees the subroutine definition? If so, why it doesn't see the undef &myf; as the second print statement?
Thanks
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
usestatements orBEGINblocks. At that point, it sees all thesubs, and notes them down in their respective packages. So now you have a&::myfin 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
printstatement is executed if&myfis defined. We know it is, because it got set at compile time. Perl then calls that function. All is well. Now youundefthat entry in the symbol table. That occurs at run time, too.After that,
defined &myfreturns 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
undefing a function. I don't see why you would remove it, unless you wanted to clean up your namespace manually.