Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^2: Hash value interpolation

by csarid (Sexton)
on Feb 16, 2009 at 21:13 UTC ( [id://744203]=note: print w/replies, xml ) Need Help??


in reply to Re: Hash value interpolation
in thread Hash value interpolation

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"; }

Replies are listed 'Best First'.
Re^3: Hash value interpolation
by ikegami (Patriarch) on Feb 16, 2009 at 21:59 UTC
    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();
      Thanks for all the help everyone... responding to ikegami's two points, the reason for the two hashes is because I wanted to simplify the code sample to focus on my problem, but the idea was to select a hash table to use based on a calculation. Also, the hash table makes the data elements much more readable for me. Is there a performance gained by using an array over the hash? Thanks gain!

        the reason for the two hashes is because I wanted to simplify the code

        You didn't do that. Your data structure is horribly complex. What's the point of having a hash for every key! (And don't say "1" and "2" could be the same string because then your goal makes no sense at all. There wouldn't be a right "hm" to fetch.)

        Is there a performance gained by using an array over the hash?

        Performance? Not really. The problem is that emulating a hash using an array is one more thing that can go wrong compared to just using an array.

Re^3: Hash value interpolation
by kyle (Abbot) on Feb 16, 2009 at 21:16 UTC

    It appears that geth() is never called. If I fix that, the output is "green".

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://744203]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-25 20:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found