in reply to Re: Naming convention for variables, subroutines, modules, etc.. and variable declaration
in thread Naming convention for variables, subroutines, modules, etc.. and variable declaration
Declare them in as small a scope as you can so there is less chance that they will be misused and their intended use is more evident. Especially this is true if you initialise the variable where it is declared.
The "use the tightest scoping possible" rule is very common these days (and therefore, probably what you should do), though just for the sake of argument...
If you use subroutine scope (always declare your variables near the beginning of your subs), you can make the main body of the code a little cleaner by eliminating the embedded "my"s scattered around. You should still have the benefit of reasonably tight lexical scoping... provided that your subroutines are short and to the point. If you need tighter scoping for some reason, maybe what you really need is more and shorter subs, eh?
I suspect that the main reason that most of us use "tight scoping" has to do with simple laziness: when we want to create a variable, we don't feel like skipping back up to a declaration section to do it. But if it improves readability a little, isn't it worth doing?
I also might make the point that perl's rules about where you're allowed to insert a "my" are a little hard to grasp.
At this point, you probably know that this works:
for my $item (@items) { ... }
chomp( my @lines = <$fh> );
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: subroutine scope vs. tightest scope
by Tanktalus (Canon) on Nov 24, 2006 at 21:04 UTC |