Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have constants like
use constant GROUPS => { A => 1, B => 2, C => 3 }; use constant A => { 1 => x, 2 => y, 3 => z }; use constant B => { 1 => x, 2 => y, 3 => z };
I want to loop through it like
while ( my ($k,$val) = each %{ +GROUPS } ) {
here is the problem I need to loop through the $k which is a constant hash, I would like to know how I can represent $k hash in the below each() ,so that it represents constants hashes A,B, etc
while ( my ($k,$val) = each ($k)) { print $k{val} ; } }
Thanks,
Shijumic

Replies are listed 'Best First'.
Re: hash and constants
by ikegami (Patriarch) on Nov 19, 2009 at 23:17 UTC
    Why it's stupid to 'use a variable as a variable name'
    my %GROUPS => ( A => 1, B => 2, C => 3 ); my %FOO = ( A => { 1 => x, 2 => y, 3 => z }, B => { 1 => x, 2 => y, 3 => z }, ); for my $group (keys %GROUPS) { my $foo = $FOO{$group}; for (keys %$foo) { print("$_ in group $group: $foo->{$_}\n"); } }

    But why does %GROUPS have values that aren't used? You probably want:

    my %GROUPS => ( A => { 1 => x, 2 => y, 3 => z }, B => { 1 => x, 2 => y, 3 => z }, ); for my $group (keys %GROUPS) { my $foo = $GROUPS{$group}; for (keys %$foo) { print("$_ in group $group: $foo->{$_}\n"); } }
Re: hash and constants
by zwon (Abbot) on Nov 19, 2009 at 23:15 UTC

    That is not a constant hash, that is a constant reference to a hash:

    use strict; use warnings; use constant GROUPS => { A => 1, B => 2, C => 3 }; GROUPS->{B} = 22; GROUPS->{D} = 'Not a constant!'; use Data::Dumper; warn Dumper [GROUPS]; __END__ $VAR1 = [ { 'A' => 1, 'D' => 'Not a constant!', 'C' => 3, 'B' => 22 } ];

    Update: have a look at Readonly

      Actually i have to correct the code I posted before. while ( my ($k,$val) = each %{ +GROUPS } ) { So my actual question is, how I can use $k in each(), so that it repre +sents A and B. while ( my ($name,$value) = each ( what I have use here?)) { print $name{value} ; } }