JIE
JIE

Reputation: 35

in perl ,how to use variable value as hash element

I am new to Perl, and can't find the answer to the question in the Learning Perl book.

For example I have a array like:

my @loop=("op1_sel","op2_sel");

and two hash table as:

my %op1_sel=(
       "bibuf","000",
       "self","101"
            );
my %op2_sel=(
        "zero","1",
        "temp","0"
            );

Now I want to use variables in the loop to loop for the hash table for a particular key for example:

foreach(@loop)
{
     print  ${$_}{"bibuf"} ;
}

But it seems not working, I know the ${$_} part is wrong, can anyone can tell me how to fix this ?

Upvotes: 1

Views: 1177

Answers (3)

zgpmax
zgpmax

Reputation: 2857

You can't refer to lexical (my) variables using the ${$foo} syntax. You could probably make it work if they were package variables, but this would not be the right way to go about it.

The right way to do it is using a nested data structure.

I can see two obvious ways of doing it. You could either make an array of op_sel containing the inner hashes directly, or create a hash of hashes, and then index into that.

So "array of hashes":

my @op_sels = (
    {
        bibuf => '000',
        self  => '101',
    },
    {
        zero => '1',
        temp => '0',
    },
);

for my $op (@op_sels) {
    print $$op{bibuf};
}

and "hash of hashes":

my %op_sels = (
    1 => {
       bibuf => '000',
       self  => '101',
    },
    2 => {
        zero => '1',
        temp => '0',
    },
);

for my $op_key (sort keys %op_sels) {
    print $op_sels{$op_key}{bibuf};
}

Upvotes: 2

Dallaylaen
Dallaylaen

Reputation: 5318

Use nested hashes. Like this:

my %op;
# put a hash reference into hash, twice
$op{op1_sel} = \%op1_sel; 
$op{op2_sel} = \%op2_sel;

# later ...
foreach (keys %op) {
    print "bibuf of $_: $op{$_}->{bibuf}\n";
};

Or, long story short, just

my %op = (
    op1_sel => { 
        foo => 1,
        bar => 2,
        # ...
    },
    op2_sel => {
        # ...
    },
};

The {} construct creates a reference to anonymous hash and is the standard way of handling nested data structures.

See also perldoc perldsc.

Upvotes: 5

core1024
core1024

Reputation: 1882

You can use eval for this.

foreach(@loop)
{
      eval "\%var = \%$_";
      print $var{"bibuf"} ;
}

Upvotes: 1

Related Questions