Would you expect the following to work?
use strict;
use vars qw($baz);
print_baz();
$baz = "Hello\n";
print_baz();
sub print_baz {print $baz};
It is the same story.
In fact this exact problem came up with a co-worker I was teaching a while ago. Even though I know very well how to fool around with BEGIN blocks, my solution was as follows:
Perl does two passes, one to parse the file, figure out
what functions are present, etc. One to actually run the
file. Both function calls and assignments happen when
it runs the code. So here it is undefined and there it is defined.
I didn't even have to suggest making the order of run-time actions be what you wanted. He found that obvious. Very simple. Consistent with how Perl works. Consistent with how everything else works. Never had a problem again.
What actual problem are you trying to solve here? That the programmer didn't expect Perl to do executable actions in the order they appear in the file? That is a matter of user expectations. Make the expectations consistent with Perl's natural order, and there is no conflict. The task doesn't need BEGIN blocks to cause things to magically happen out of order. The programmer doesn't need to complicate their code with that crap. Just ask Perl to do things in the order you actually want them done!
That results in simpler code, simpler logic, less mechanics for the programmer to think through and worry about, why wouldn't this be the right solution?
I am now even less convinced than I was that there is a real need being addressed by using BEGIN blocks. So far every example that you have shown using it has been a sign of something I would prefer to see solved in another way! |