Reputation: 911
for example:
#!/usr/bin/perl
use Data::Dumper;
main();
my %h = (
name => 'abc',
value => '123',
);
sub main {
print "Dumping the hash...\n";
print Dumper(%h);
}
1;
the result is:
Dumping the hash...
So perl can call main before it be implemented, why it doesn't know the global var %h which even define early than main()?
Upvotes: 0
Views: 35
Reputation: 385789
The my
and the =
are unrelated. In CS jargon, %h
is actually defined before main
is called (my
). You're asking why the assignment wasn't performed (=
).
main()
is executed before the assignment to %h
because main()
is found before the assignment to %h
in the code.
It's exactly the same reason that
print("abc\n");
print("def\n");
will never print
def
abc
Upvotes: 2
Reputation: 241858
There are basically two phases of processing of every Perl program: the compilation phase and the run phase. During the compilation phase, my
and sub
are processed, so Perl now knows you'll be using the globally accessible lexical variable %h
. It's not populated, though - that would happen during the run phase. But, main
is called before %h
is populated.
Upvotes: 2