OK, so for arrays and hashes there is no need. This is just about scalars then.
I certainly don't advocate initialization for it's own sake simply to shutup warnings about uninitialized variables.
An idiom I like to use in subs where something like:
sub foo {
my $retval = 0;
<... lots of code here ...>
return $retval; # This is the only return in the sub
}
I like to use this for several reasons
1) It's guaranteed that the sub will always return a value.
2) There is a single entry/exit point. Apart from it being simple, I know that this makes it easier for compilers/interpreters to prove certain things about your code. Can't say I know if it will make any difference whatsoever in Perl, but it often does in C-like languages.
3) The initial value of 0 is assumed to be the failure case, putting the burden of 'proof' to set $retval properly. Hope to see a failure case quicker this way.
When possible, I also prefer to see code more like:
...
my $whatever = some_sub();
I find the 'classic C' style of declaring lots of variables at the top of your routine, then using them in the body, to be harder to follow. e.g.:
my $var1;
my $var2;
my $var3;
my @list;
my %hash;
...
Worse if they're all global! I don't like jumping back and forth, or wondering where variables got their values (or what they were initialized as/from). Arguably if the code was done well enough in the first place it would already be pretty short and there would be no problem, but unfortunately I see this all the time. IMO it's more error-prone. If that's what you mean when you said "declare variables to minimize their scope" then I agree.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.