Amit Saxena wrote:
> Hi all,
>
> I recently had one requirement where I needed to get the key in a hash on
> the basis of supplied value.
>
> There is one additional information that there is one to one mapping between
> the keys and the values.
>
> I was able to do that by defining a extra array and hash variables as shown
> in the program below but I feel this approach will not work for all
> scenarios like :-
>
> 1. When the value of a particular key is undef in the original hash.
>
> 2. When there are nested data structures.
>
> I have pasted the program as well as the output over here.
>
> *Prompt#* *cat test_hash_reverse.pl*
> #! /usr/bin/perl
>
> use strict;
> use warnings;
>
> my %h1 =
> (
> "N" => "North",
> "E" => "East",
> "W" => "West",
> "S" => "South",
> "C" => "Central"
> );
>
> print "The Hash h1 is printed below :-\n";
>
> foreach my $var1 (keys %h1)
> {
> print "\t[$var1] => [$h1{$var1}]\n";
> }
>
> my @arr1 = %h1;
>
> print "The Array arr1 as initialized from the Hash h1 is printed below
> :-\n";
>
> print "@arr1\n";
>
> my @arr2 = reverse (@arr1);
>
> print "The Array arr2 as initialized from the reverse of the Array arr1 is
> printed below :-\n";
>
> print "@arr2\n";
>
> my %h2 = @arr2;
>
> print "The Hash h2 as initialized from the Array arr2 is printed below
> :-\n";
>
> foreach my $var2 (keys %h2)
> {
> print "\t[$var2] => [$h2{$var2}]\n";
> }
>
> *Prompt #* *perl test_hash_reverse.pl*
> The Hash h1 is printed below :-
> [S] => [South]
> [W] => [West]
> [C] => [Central]
> [N] => [North]
> [E] => [East]
> The Array arr1 as initialized from the Hash h1 is printed below :-
> S South W West C Central N North E East
> The Array arr2 as initialized from the reverse of the Array arr1 is printed
> below :-
> East E North N Central C West W South S
> The Hash h2 as initialized from the Array arr2 is printed below :-
> [West] => [W]
> [Central] => [C]
> [South] => [S]
> [North] => [N]
> [East] => [E]
> *Prompt #*
>
>
You may as well just say
my %h2 = reverse %h1;
but what is your question?
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/