... I have always written code with the subroutines at the end
Curiously, I've always done the reverse, perhaps because in C you must declare a function
before calling it, and I wanted to avoid the tedious duplication of
writing forward declarations for my locally defined C functions called from
main.
Even in Perl, order matters, for example:
use strict;
use warnings;
# mainline--------------------------
mygreeting "world";
# subroutines ----------------------
sub mygreeting {
my $salutation = shift;
print "hello $salutation\n";
}
fails to compile:
String found where operator expected at g1.pl line 5, near "mygreeting
+ "world""
(Do you need to predeclare mygreeting?)
syntax error at g1.pl line 5, near "mygreeting "world""
because the compiler is yet to see the mygreeting subroutine definition.
Though you can fix with the compiler's predeclare mygreeting suggestion,
or by hoisting the mygreeting subroutine definition to the top of the file,
I prefer to avoid these sorts of compilation glitches simply by following
a simple rule: "always call user-defined subroutines with parens".
Here the parens give the compiler a strong hint that mygreeting is a subroutine,
even though it is yet to parse its definition.
That is, this compilation error is easily remedied simply by adding parens to the call:
mygreeting("world");
As a matter of style, some folks find the code easier to read when user-defined functions
are always called with parens and built-in functions are always called without parens ...
I see Perl Best Practices
endorses this style via:
- Don’t use unnecessary parentheses for builtins and ‘honorary’ builtins (item 4)
- Call subroutines with parentheses but without a leading & (item 113)