hash-inversion-by-reversing-the-values-to-keys-and-keys-to-values-in-perl
Method 1:
%hash=(9,5,2,1,4,6);
@final5{values %hash} = keys %hash;
print @final5;
Method 2:
print @final5;
Method 2:
$z=0;
%hash=(9,5,2,1,7,6);
%hash=(9,5,2,1,7,6);
foreach((sort values %hash)) {
$final5{ $_ } = (sort keys %hash)[$z];
$z++;
}
Method 3:
%hash=(9,5,2,1,4,6);
@first1=values %hash;
@second2=keys %hash;
foreach my $a1 (@first1)
{
my $a2= shift @second2;
$final3{ $a1 } = $a2;
}
Method 4:
%hash=(9,5,2,1,4,6);
@first=values %hash;
@second=keys %hash;
for($j = 0; $j < @first; $j++)
{
$final{$first[$j]} = $second[$j];
}
Method 5:
%hash=(9,5,6,1);
@first_1=values %hash;
@second_1=keys %hash;
while( @first_1 || @second_1)
{
my $a1= shift @first_1 || "Perl_Methods_Master";
my $a2= shift @second_1 || "Perl_Methods_Master";
$final{$a1} = $a2;
}
Method 6:
%hash=(9,5,2,1,4,6);
@first1=values %hash;
@second2=keys %hash;
while( @first1 && @second2)
{
my $b1= shift @first1;
my $b2= shift @second2;
$final{$b1} = $b2;
}
Method 7:
%hash=(9,5,2,1,4,6);
@first2=values %hash;
@second1=keys %hash;
while (@first2 || @second1)
{
$final{shift @first2} = shift @second1;
}
Method 8:
%hash=(9,5,2,1,4,6);
@first1=values %hash;
@second1=keys %hash;
$final{shift @first1}=shift(@second1) while @second1;
Method 9:
%final1=(9,5,2,1,4,6);
@first2=values %final1;
@second2=keys %final1;
$i=0;
%final2=map {$first[$i++],$_; } @second2;
Method 10:
%final5=(9,5,2,1,4,6);
while (($k, $v) = each %final5)
{
$final2{$v}=$k;
}
Method 11:
%final5=(9,5,2,1,4,6);
%final5 = reverse %final5;
.
Labels: Inverting a Hash's Key and Values in Perl, kaavannan perl blogspot