(Assume use strict; use warnings;
throughout this question.)
I am exploring the usage of sub
.
sub bb { print @_; }
bb 'a';
This works as expected. The parenthesis is optional, like with many other functions, like print, open
etc.
However, this causes a compilation error:
bb 'a';
sub bb { print @_; }
String found where operator expected at t13.pl line 4, near "bb 'a'"
(Do you need to predeclare bb?)
syntax error at t13.pl line 4, near "bb 'a'"
Execution of t13.pl aborted due to compilation errors.
But this does not:
bb('a');
sub bb { print @_; }
Similarly, a sub without args, such as:
special_print;
my special_print { print $some_stuff }
Will cause this error:
Bareword "special_print" not allowed while "strict subs" in use at t13.pl line 6.
Execution of t13.pl aborted due to compilation errors.
Ways to alleviate this particular error is:
- Put & before the sub name, e.g.
&special_print
- Put empty parenthesis after sub name, e.g.
special_print()
- Predeclare
special_print
withsub special_print
at the top of the script. - Call
special_print
after the sub declaration.
My question is, why this special treatment? If I can use a sub globally within the script, why can't I use it any way I want it? Is there a logic to sub
being implemented this way?
ETA: I know how I can fix it. I want to know the logic behind this.