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. | [reply] [d/l] |
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?
| [reply] [d/l] [select] |
Just a bit of weekend golf/obfu....
s//$prefix/for values%hash;
-Blake
| [reply] [d/l] |
In this case, $prefix is not a global, because you've my'ed it. But I know what you're saying - you don't want to clutter your code with unneeded declarations. The rule of thumb has to be that the best answer is the most fitting one. Does 'abcd' have any particular individual significance (so it might change in future), or is it just coincidence that it forms the start of all your strings (in which case it won't)? | [reply] [d/l] |
| [reply] [d/l] |