A am real new to Perl. My background is Modula2 and Bash scripts.
Please premit a newbie question:
1) Under Modula2, best practice (or my practice) was from top
to bottom
a) make my declarations (which variable did what, etc.),
b) write all my modules and functions, and
c) in the body, place my code.
Is this also the proper structure under Perl as well?
I don't think so. In fact I think this is a particularly bad structure
and one of the reasons why I don't like Pascal-like languages is that
they force this structure on the programmer.
I believe (and I know many other perl-programmers agree) that variables
should always be declared in the smallest possible scope. I.e., don't do
something like this:
my $some_variable;
sub a_subroutine {
...
}
# many more subroutines - hundreds of lines of code
for (...) {
if (...) {
# $some_variable is only used in this block:
$some_variable = get_some_value();
some_code();
do_something_with($some_variable);
more_code();
}
}
There are hundreds of lines of code where $some_variable could be
accessed and changed. When you look at the code you have no idea whether
you are passing the same value to do_something_with() as you received
from get_some_value(). $some_variable might have been changed by
some_code() or any function called by it.
Instead, write it like this:
sub a_subroutine {
...
}
# many more subroutines - hundreds of lines of code
for (...) {
if (...) {
# $some_variable is only used in this block:
my $some_variable = get_some_value();
some_code();
do_something_with($some_variable);
more_code();
}
}
That way $some_variable is visible only visible inside of the if block.
Nothing outside can change it unless $some_variable is explicitely
passed to it (that is do_something_with() could change $some_variable).
Browsing through Conway's "Perl Best Practice", I was surprised that I
couldn't find that advice, although he does follow that style. Maybe he
thought that's so self-evident that he doesn't have to spell it out.
hp