Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

gav (2710)

gav
  (email not shown publicly)
http://www.estey.com/
AOL IM: flufflegavin (Add Buddy, Send Message)

Hacker in NYC.

Journal of gav (2710)

Wednesday July 14, 2004
02:37 PM

Pointless temporary variables

[ #19852 ]

One of my pet peeves is pointless temporary variables, they often just clutter things up. Consider this example (pulled from production code) that is crying out for some refactoring.

my $keywords;
@$keywords = split ' ', $something;
foreach my $word (@$keywords) {
    # ...
}

vs.

foreach my $word (split ' ', $something) {
    # ...
}

Isn't this much easier to understand?

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • the original author wanted to be able to view @$keywords in a debugger, to see the result of the split.

    I've split up operations sometimes, placing an intermediary step in between, to facilitate debugging.

    Just a thought.
  • Both examples make sense to me, but if you've got Perl coders who don't code Perl *all* the time, I think the second example would require a few more brain cycles than the the first. This is especially true if there's one part they don't remember--like the fact that split returns a list. The temporary variable re-enforces this by showing it. Besides, memory is cheap :)
  • Folks advocate well named temp variables for clarity, similar to well named functions. Its not obvious from glancing at just a split that you're getting a list of keywords. It is obvious from "my @keywords = split ...". However, "foreach my $keyword (split ...)" works just as well.

    I have seen this concept abused.

    sub foo {
        my $thing = shift;
        my $foo = ...some simple calc...;
        return $foo;
    }

    Other times folks start out with the long hand version using temp variables