Re: Hash value interpolation
by ikegami (Patriarch) on Feb 16, 2009 at 20:44 UTC
|
my $ht = \%h1;
while ( my ( $key, $value ) = each(%$ht) ) {
...
}
| [reply] [d/l] |
|
|
Thanks ikegami, your idea gets me closer however, I get no output. Looks like I'm still doing something incorrect.
Below is my actual test script:
use warnings;
use strict;
my $COLOR=2;
my $hm="";
my $ht="";
my %h1 = (
"1" => "blue"
);
my %h2 = (
"2" => "green"
);
if ( $COLOR == 1 ) {
$ht=\%h1;
}
elsif ( $COLOR == 2 ) {
$ht=\%h2;
}
sub geth {
while ((my $key, my $value) = each(%$ht)) {
if ( $key == $COLOR ) {
$hm=$value;
}
}
print "$hm\n";
}
| [reply] [d/l] |
|
|
I don't know why you have two hashes in the first place.
my %colors = (
"1" => "blue",
"2" => "green",
);
my $COLOR = 2; # 1..2
sub geth {
print "$colors{$COLOR}\n";
}
geth();
Or why you aren't using an array.
my @colors = (
"blue",
"green",
);
my $COLOR = 1; # 0..1
sub geth {
print "$colors[$COLOR]\n";
}
geth();
| [reply] [d/l] [select] |
|
|
|
|
|
|
|
| [reply] [d/l] |
|
|
Is it just me or is each an usability fail? I prefer traversing hashes with either keys or values.
my $ht = \%h1;
for my $key ( keys %{$ht} ){
my $val = $ht->{$key};
...
}
print+qq(\L@{[ref\&@]}@{['@'x7^'!#2/"!4']});
| [reply] [d/l] [select] |
|
|
The use of each is that it's not a memory hog. When you loop over keys, Perl has somewhere built a list of all the keys in the hash. This is especially disastrous when the hash is tied to some huge data set.
The real problem with each is that every hash has only one iterator, and if you drop out of a loop that's walking the hash, the next loop that tries to walk that hash will start where the first left off.
| [reply] |
|
|
|
|
|
|
|
Re: Hash value interpolation
by csarid (Sexton) on Feb 16, 2009 at 21:41 UTC
|
qSorry if I double posted...
Thanks Ikegami, your idea/solution gets me further; however, now I do not get any output. Looks like I'm still doing something wrong. below is the test code I'm using:
would apreciate the extra help.
Thanks again!
use warnings;
use strict;
my $COLOR=2;
my $hm="";
my $ht="";
my %h1 = (
"1" => "blue"
);
my %h2 = (
"2" => "green"
);
if ( $COLOR == 1 ) {
$ht=\%h1;
}
elsif ( $COLOR == 2 ) {
$ht=\%h2;
}
sub geth {
while ((my $key, my $value) = each(%$ht)) {
if ( $key == $COLOR ) {
$hm=$value;
}
}
print "$hm\n";
}
| [reply] [d/l] |
|
|
| [reply] |
|
|
I can't believe I missed that. Thanks Jason for pointing that out and my oppologies for the oversight!
It actually works after all. Thanks to Ikegami as well for the original solution
| [reply] |