0

I have a Perl file code state.pl where I am trying to retrieve full name of State based on State code from Hash of Arrays. Following is the code:

my $all_state_details = {
          IN => [
                  [
                    "AP",
                    "Andhra Pradesh"
                  ],
                  [
                    "AN",
                    "Andaman and Nicobar Islands"
                  ],
                  [
                    "AR",
                    "Arunachal Pradesh"
                  ],
                ],
        US => [
                  [
                    "AL",
                    "Alabama"
                  ],
                  [
                    "AK",
                    "Alaska"
                  ],
                  [
                    "AS",
                    "American Samoa"
                  ],
                ],
        };

my $state = 'AN';
my $country = 'IN';

my @states = $all_state_details->{$country};
my @state_name = grep { $_->[0] eq $state } @states;
print @state_name;

When I run the script, I get the blank output

I want the output as just:

Andaman and Nicobar Islands
SaAsh Techs
  • 169
  • 10

2 Answers2

2

The @{ ... } dereference operation is necessary to convert the array reference in $all_state_details->{$country} into an array suitable for use with grep.

print map { $_->[1] } 
     grep { $_->[0] eq $state } @{$all_state_details->{$country}};
mob
  • 117,087
  • 18
  • 149
  • 283
  • Thanks a lot but I tried this ```my $state_name = map { $_->[1] } grep { $_->[0] eq $state } @{$all_state_details->{$country}}; print $state_name``` but $state_name value is returning 1 – SaAsh Techs Aug 24 '19 at 19:17
  • See https://stackoverflow.com/questions/2126365/whats-the-difference-between-my-variablename-and-my-variablename-in-perl – mob Aug 24 '19 at 19:37
  • Re "*into an array suitable for use with `grep`*", Into the individual scalars contained in the array, as suitable for `grep` – ikegami Aug 24 '19 at 19:59
0

The right way to do this kind of lookup is with a hash of hashes.

e.g.

%all_state_details = (
      IN => {
                "AP" => "Andhra Pradesh",
                "AN" => "Andaman and Nicobar Islands",
            },
);

Then you just do a direct lookup.

print $all_state_details{IN}{AN};

Read https://perldoc.perl.org/perldsc.html#HASHES-OF-HASHES

HTH

lordadmira
  • 1,807
  • 5
  • 14