2010-10-15 117 views

回答

1
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" }; 

my $index; 
my $find = "B"; 
foreach my $key (keys %{ $hashtest{1} }) { 
    if($hashtest{1}{$key} eq $find) { 
     $index = $key; 
     last; 
    } 
} 

print "$find $index\n"; 
-1
$hashtest{1}{1}; 
+1

但是,如果我知道的價值,我想索引?例如,我想知道哈希{1}的'A'的「索引」? – user476918 2010-10-15 13:45:00

3

根據你對其他答覆 可以扭轉的哈希評論,(即交換密鑰和值。) 。

但要小心,只有在您確定 之後才能做到這一點,原始 中沒有重複值,因爲此操作僅保留其中的一個。

#!/usr/bin/perl 
use 5.10.1; 
use warnings; 
use strict; 

my %hashtest; 
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" }; 
my %rev = reverse %{$hashtest{1}}; 
say $rev{B}; 

輸出:

0

既然你已經使用號碼的散列鍵,在我看來,你應該使用數組來代替。否則,在反轉散列時,您將丟失重複的鍵。

示例代碼:

use strict; 
use warnings; 

use List::MoreUtils 'first_index'; 

my $find = 'A'; 
my @array = qw{ A B C }; 
my $index = first_index { $_ eq $find } @array; 

Perl Data Structures Cookbook將幫助您瞭解在Perl的數據結構。

0

如果所有的按鍵都是整數,你最想處理數組,而不是哈希:

$array[1] = [ qw(A B C) ]; # Another way of saying [ 'A', 'B', 'C' ] 

print $array[1][1];   # prints 'B'