in reply to A question of style - declaring lexicals
I always declare lexicals at the point of first assignment, if possible.
The issue almost becomes irrelevant if one keeps lexical scopes short. Of course, this is often not practical. If I do find myself with a block several pages long, I'll revert to style #1 for variables that are in fact used "throughout" that scope, even if first assignment isn't at the top of the scope. But if, in a pages-long block, there is a valid need for name re-use but not value longevity, I will often introduce bare blocks just for the purpose of constraining the scope of distinct variables, rather than recycle a single variable. E.g.
Oftentimes, if the net effect of a section of code is to produce a value, a do block is useful for introducing an "artificial" scope. E.g. instead of a plain bare block like this,{ # long block begin . . { my $name = 'foo'; . . } . . { my $name = 'bar'; . . } . . }
I might use a do block, like this, which obviates an auxiliary variable:my @lines; { my $fh = new IO::File "< $infile"; @lines = <$fh>; } for ( @lines ) { ...
(Note that lexical scopes are also useful for constraining the effects of local operators.)for ( do { my $fh = new IO::File "< $infile"; <$fh> } ) { ...
|
|---|