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

Hi there,

have this tiny but overly irritating issue where i would like to choose iterated %hash by scalar value. So if $choise variable contains string "computerAttributes", iterate through %computerAttributes. This way i can have only one foreach loop defined in the program, but several hashes to choose from. Must have a brain malfunction or something, but i just can't figure this one out.

#!/usr/bin/perl -w use strict; my $choice = 'computerAttributes'; my %computerAttributes = ( cn => 'Common Name (eg. John Doe)', distinguishedName => 'Computer distinguishedname (dn) representing o +bject location in LDAP-directory', lastLogOff => 'Last time LDAP-directory received logoff message from + system' ); my %userAttributes = ( cn => 'Common Name (eg. laptop1)', sn => 'Surename', displayName => 'First and lastname', title => '' ); foreach (my $key = keys %($choice)) { print "$key\n"; }

Replies are listed 'Best First'.
Re: Choosing %hash by scalar value
by NetWallah (Canon) on Feb 05, 2006 at 22:58 UTC
    Here is another way - Ref to existing hash ..

    Move "choice" declaration down, and change last few lines to :

    my $choice = \%computerAttributes; foreach my $key ( keys %{$choice}) { print "$key\n"; }
    Although this does not exactly map to your problem description (since $choice is NOT a string anymore), I suggest that this is a less error-prone approach, and you should structure your code to use this mechanism, if you possibly can. If not, the HOH solution described above is a good choice.

         "For every complex problem, there is a simple answer ... and it is wrong." --H.L. Mencken

      Great! Using references is without a doubt the best way to achieve my goal. Thank you.
Re: Choosing %hash by scalar value
by tirwhan (Abbot) on Feb 05, 2006 at 22:46 UTC

    Use a hash of hashes

    my %attributes = ( computerAttributes => { cn => 'Common Name (eg. John Doe)', distinguishedName => 'Computer distinguishedname (dn) represen +ting object location in LDAP-directory', lastLogOff => 'Last time LDAP-directory received logoff + message from system' }, userAttributes => { cn => 'Common Name (eg. laptop1)', sn => 'Surename', displayName => 'First and lastname', title => '' } ) for my $key (keys %{$attributes{$choice}}) { print "Key: $key\tValue: $attributes{$choice}->{$key}\n"; }
    Update: showed how to print key-value pair, at ysth's suggestion.

    All dogma is stupid.