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

Hi Monks!
I am trying to match a value I get from an XML file and compare this value and find a match with values in a hash. I have this sample code and I hope it will explain what I am trying to do.
#!/usr/bin/perl -w use strict; my @code_reference = qw(aaaa qqqqq 7781q 09888 wetrt); foreach my $code(@code_reference) { my $place = "http://mylocation?param=" . $code ; my $data = XML::TreePP->new(); my $all_data = $data->parsehttp( GET => $place ); # This will return a different value for each "@code_reference". It co +uld be like: # "Value: AE" "Value: YY" "Value: C" "Value: P" "Value: PP" from my XM +L my $got_data=$all_data->{xml}->{code}->{"-data"}; # I have this hash, that I am trying to match lets say, if I got "Valu +e: AE", I want to # find the value in the hash the match "AE" and print. my %wind_dir = ( 'Loc A' => 'AA,A,AE,AB,BB,EA,C', 'Loc B' => 'TT,T,AE,B', 'Loc C' =>'PP,P,PA', 'Loc D' =>'YY, TT,P,OP,QA' ); # It should print: Loc A found AE # Loc B found AE
How can I do that, I hope I am been clear with this sample code to illustrate what I am trying to do.
Thanks for the help!

Replies are listed 'Best First'.
Re: Matching value in hash help!
by ikegami (Patriarch) on Sep 24, 2010 at 01:54 UTC

    Your hash is inside out.

    my %locs_by_wind_dir; for my $loc (keys(%wind_dir)) { for my $wind (split /,/, $wind_dir{$loc}) { push @{ $locs_by_wind_dir{$wind} }, $loc; } } print("$_\n") for @{ $locs_by_wind_dir{'AE'} }; # Loc A, Loc B
      What do you mean by "Your hash is inside out."?

        It means that, in the hash you're currently using, the values you're looking for are in keys, and the keys you're searching with are in values.

        More useulf is a hash that looks like the following:

        AA => "Loc A", BB => "Loc A", TT => "Loc B", T => "Loc B", PP => "Loc C", # etc
        Compare the output of the following
        use Data::Dumper qw( Dumper ); print(Dumper(\%wind_dir)); print(Dumper(\%locs_by_wind_dir));