Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can get subroutine address before it is declared without error?

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?

like image 678
Eugen Konkov Avatar asked Jul 04 '17 12:07

Eugen Konkov


Video Answer


1 Answers

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))
like image 123
ikegami Avatar answered Nov 15 '22 07:11

ikegami