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

my %citystate; my %citycountry; my %country; my %airportCode; my %geonameid; if ($line =~ /.*Cannot find valid (destination) for type:(.*)=(.*)/) { my $type = $2; my $key = $3; if ($type =~ /citystate/) { $citystate{$key} = ""; } elsif ($type =~ /citycountry/) { $citycountry{$key} = ""; } elsif ($type =~ /country/) { $country{$key} = ""; } elsif ($type =~ /airportCode/) { $airportCode{$key} = ""; } elsif ($type =~ /geonameid/) { $geonameid{$key} = ""; } } for my $key ( keys %citystate ) { $fhdest -> print("<p>$key</p>"); } for my $key ( keys %citycountry ) { $fhdest -> print("<p>$key</p>"); } for my $key ( keys %airportCode ) { $fhdest -> print("<p>$key</p>"); }
In the above code instead of using if-else conditions can I use something like $$type{$key} / $"$type"{$key} ?

Replies are listed 'Best First'.
Re: dynamic hash name
by Tanktalus (Canon) on Feb 03, 2009 at 00:26 UTC

    You can, but it involves symbolic references that you really shouldn't bother with until you know why.

    Instead, you need a symbol table of your own. Either:

    my %destinations; if ($line =~ /.*Cannot find valid (destination) for type:(.*)=(.*)/) { $destinations{$type}{$key} = ""; }
    or
    my %citystate; my %citycountry; my %country; my %airportCode; my %geonameid; my %symboltable = ( citystate => \%citystate, citycountry => \%citycountry, country => \%country, airportCode => \%airportCode, geonameid => \%geonameid ); if ($line =~ /.*Cannot find valid (destination) for type:(.*)=(.*)/) { $symboltable{$type}{$key} = "" }
    The first option is better. (Advanced monks may disagree, but for beginners, it simply is better. You can learn the second way when you really understand the first way and its limitations.)

      So for the first option: How do I iterate? Because at the end this is what I want to do.
      for my $key ( keys %citystate ) { $fhdest -> print("<p>$key</p>"); } for my $key ( keys %citycountry ) { $fhdest -> print("<p>$key</p>"); } for my $key ( keys %airportCode ) { $fhdest -> print("<p>$key</p>"); }
        $data{citystate} contains a reference to a hash, so where you had
        for my $key ( keys %citystate ) {
        you now use
        for my $key ( keys %{ $data{citystate} } ) {
Re: dynamic hash name
by toolic (Bishop) on Feb 03, 2009 at 00:25 UTC
    It would be cleaner to use a hash-of-hash-type data structure, something like:
    my %data; ... if ($type =~ /citystate/) { $data{citystate}{$key}; } elsif ($type =~ /citycountry/) { $data{citycountry}{$key}; } elsif ($type =~ /country/) { $data{country}{$key}; ...