Sunday, May 26, 2013

Perl experience - misc

In Perl, when to call subroutine with ampersand or parentheses. It's always confusing to me. Finally, I have some conclusion on it.

1. if perl can see the subroutine definition before invocation, ampersand can be omitted.
2. if perl can tell from the syntax that it's a subroutine call, for example sub(), ampersand can be omitted.
3. Otherwise, use &. Or you will get compilation error when using strict.

Correct Example
#!/usr/bin/env perl
use strict;
use warnings;

&sub1;

#
# the parentheses tell it's subroutine.
#
sub1();

sub sub1 { print "sub1\n"; }

#
# the subroutine defintion before invocation.
#
sub1;

Incorrect Example
#!/usr/bin/env perl
use strict;
use warnings;
sub1;
sub sub1 { print "sub1\n"; }

The Perl will complain
Bareword "sub1" not allowed while "strict subs" in use at sub.pl

No comments: