2016-02-10 36 views
2

我剛剛開始使用Perl腳本,同時製作數組並從哈希變量中獲取數組。我得到一個尷尬的輸出。哈希變量和Perl中的數組給出了一個尷尬的輸出

代碼是在這裏:

%name= ("xyz",1 ,"is",2, "my",3,"name",4); 
%copy=%name; 
$size=%name; 
print " your rank is : $copy{'xyz'}"; 
print " \n"; 
print " the size of the array is : $size"; 

輸出即將爲:

your rank is : 1 
the size of the array is : 3/8 

爲什麼數組的大小爲3/8?

+0

有一個在你的代碼沒有數組。你認爲哪個變量是一個數組? –

回答

4

它關心的是哈希的內部信息,請檢查perl documentation

如果你評估在標量上下文的哈希,它返回如果哈希爲空,假的。如果有任何鍵/值對,則返回true;更準確地說,返回的值是一個字符串,由使用的存儲段數和分配的存儲段數組成,並由斜槓分隔。只有找出Perl的內部哈希算法在數據集上執行效果不佳,這才非常有用。

因此,這裏的具體意思是說你有8個桶分配在哈希中,其中三個被使用。

爲了獲得規模應用:

$size = keys %hash; # scalar is implicit here 
print(scalar keys %hash); 
2

如果你想使用scalarkeys找出鍵/值的數量:

my %name= ("xyz",1 ,"is",2, "my",3,"name",4); 

my %copy = %name; 

my $size = scalar keys %name; 

print "your rank is : $copy{'xyz'}\n"; 
print "the size of the array is : $size\n";