What benefit has the "sub main ... &main();" approach (sub-main-pattern) in Perl?
A few years back, I have adopted the following "pattern" for all except the most simple of my Perl scripts: (I don't even remember where I saw it 开发者_JAVA百科first, it certainly wasn't my genuine idea.)
use strict;
...
sub main {
...
}
... possibly more subs ...
... at the end of the file:
#############
# Call main #
&main();
#############
Is there any benefit to this? I find the code a little cleaner, but otherwise I'm not sure this has any purpose other that to make the C programmer in me happy :-)
Any insights from Perl experts and power users appreciated. (I am certainly neither)
It's a known idiom to limit scope. This is discussed in https://stackoverflow.com/q/1183876#comment-1012787 ff. and http://use.perl.org/comments.pl?sid=43991&cid=70918 ff.
It provides a scope to avoid accidentally using the wrong variables in subs. { ... }
would also do this, but using a sub allows the main code to be placed at the top of the file while still executing other initialisation code in the file.
Personally, I've have used
{
... # Extract command line switches from @ARGV
... # Perform input validation
exit(main(@ARGV));
}
Benefit? No, not unless you need to re-use the main sub. In some cases it might perhaps ease readability, but I doubt it.
One thing that is different is that commands such as:
my $arg = shift;
Will affect @_
instead of @ARGV
, and @ARGV
will not automatically be passed on to main()
. @ARGV
will still be visible inside the sub, but you will have to shift it explicitly shift @ARGV
.
One advantage might be that it makes it easier to turn your program into a modulino.
Having done a lot of Perl I'd say it's just something that makes you happy. I doubt it's any faster or slower.
Just to make my answer somewhat useful I will point out that you don't need the &
on your sub call. &
makes @_
visible to the sub, but empty parens negates that.
精彩评论