in reply to Is a global variable better than repetition within variables?

c: this is actually a complicated question and is dependant on your program's particular needs. First, you have to ask yourself: "how frequently is this occurring?". If this was merely a constant value, such as PI, then yes, I'd extract it out and declare it elsewhere if I used it more than once. However, if this is part of another variable and you only have two keys referencing it, well, you may be adding complexity for a false benefit.

One key test is a question I always ask myself when I designing a database schema: are my data elements related, or merely similar? What if I have five guys named John who live at the same address? Their addresses are related, so properly they might need to be in another table. Their first names, however, are similar, but not related. I wouldn't want to abstract those out into another table. You have the same issue here. Is that prefix a coincidence or not? If it is and you abstract it out, you're shooting yourself in the foot. If you only have a couple of hash elements, you may be shooting yourself in the foot. If you have hundreds of them and they are related, you're doing yourself a favor:

my $prefix = 'abcd'; my %hash = ( a => 1234, b => 5678, . . . zzz => 666 ); %hash = map { $_, $prefix.$hash{$_} } keys %hash;

That, I think, is a win. Otherwise, it may be more trouble than it's worth. Of course, if you're adding the hash keys in several different places, then the prefix idea might very well be a good thing even if you do only have a couple of items.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

  • Comment on (Ovid) Re: Is a global variable better than repetition within variables?
  • Download Code

Replies are listed 'Best First'.
Re: (Ovid) Re: Is a global variable better than repetition within variables?
by Anonymous Monk on Jan 27, 2002 at 08:25 UTC
    As of perl5.6 values() returns the actual variables and not copies. This means that you can do fancy stuff like     $_ = $prefix . $_ foreach values %hash; Actually, I'd even prefer     $hash{$_} = $prefix . $hash{$_} foreach keys %hash; over the map() approach, since as you say, there can be hundreds of them (or 18278 as in your example! ;)) and building up another list of that would be a waste. Or is there any funky optimization going on that I'm unaware of?
      Just a bit of weekend golf/obfu....
      s//$prefix/for values%hash;

      -Blake

        I was about to suggest that too, just for fun. But I chose not to. Didn't want to start a golf/obfu thread. :)

        Anyhow, there's a bug in your code. You need to have something as pattern. Otherwise the empty pattern magic will kick in.

        -Anomo