I have next program:
use warnings;
use strict;
BEGIN {
print \&mysub;
}
sub mysub {};
print \&mysub;
Its output:
CODE(0x118e890)CODE(0x118e890)
The BEGIN
block is processed in compile time. At that point definition of sub mysub
is not seen by compiler yet. But program still prints right subroutine address, which it will have when defined.
Why I do not get error here? Is this some sort of autovivification?
Yes, this is a form of autovivification. A stub is created when a reference to the sub is required and the sub doesn't exist.
use strict;
use warnings qw( all );
use feature qw( say );
sub test {
say defined(&mysub) ? "defined (".\&mysub.")"
: exists(&mysub) ? "exists (".\&mysub.")"
: "doesn't exist";
}
test();
my $ref = \&mysub;
test();
eval("sub mysub { } 1") or die($@);
test();
Output:
doesn't exist
exists (CODE(0xab8cd8))
defined (CODE(0xab8cd8))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With