If your subroutine or function definition does not include a parameter list or parentheses, there are three ways to call it:
print( ) is a function defined in a module that loads before your program. The parentheses of the parameter list thus can be omitted and the string value following the print statement will passed as a parameter. User-defined functions work the same way. If your program consists of the following lines, it will print the "Hello" message:print $myString;
printMe( ) is defined before it is called and the string will be passed to the subroutine. The following code, however, will not execute:sub printMe { print "@_\n"; } printMe "Hello function!\n";
Here printMe "string" is called before the subroutine is defined. (The interpreter reads the program line by line.) This will create an compilation error.printMe "Hello subroutine!\n"; sub printMe { print "@_\n"; }
will work (subroutine is defined before it's called), butsub printMe() { print "Hello\n"; } printMe;
will not.printMe; sub printMe() { print "Hello\n"; }
will not crash, and neither willprintMe(); sub printMe() { print "Hello\n"; }
The reason for this is as follows: If the subroutine call does not include parentheses or the prepended subroutine symbol, Perl will look upon the subroutine name as an operator. If the subroutine hasn't been defined yet, it doesn't know what to do with it. However, Perl allows you to define subroutines anywhere in the program. So, if you append parentheses or prepend the subroutine symbol to the subroutine name, Perl knows that this statement is supposed to be a subroutine call and waits until all subroutines are loaded.&printMe; sub printMe() { print "Hello\n"; }
Confused? There's good reason to be confused. Doing one thing n different ways is not good programming practice. Recommendation: Be explicit and consistent. Always include explicit subroutine declarations in your code and call subroutines as subroutines, not just by name. It will make your code more readable and a lot easier to maintain.