2017-02-13 50 views
2

任何人都可以幫助知道如何計數沒有。密鑰中的密碼,在PERL 6?尋找沒有手動循環的東西。如何獲得no的數量。密鑰在perl 6%HASH中?

在此先感謝!

編輯:嘗試以下目前爲止,但沒有運氣。

my %hash = 1 => "one", 2 => <21,22,23>, 3 => "three" ; 

my $count = %hash.keys [ makes it a flat list ] 
my $count = %hash.count [no such method] 
my $count = keys %hash [provides all the keys but not the count] 

回答

9

在perl5中,您只需將一個散列投射到一個標量上即可成爲計數。你可以這樣做,在perl6太:

%hash.Int; 
# => 3 
+%hash 
# => 3 

還你elems的方法:

%hash.elems; 
# => 3 
+1

在Perl 5中,如果您將哈希強制轉換爲標量,您會得到桶。 –

0

這個答案哈希是OP編輯之前發佈:

你的哈希初始化有問題

my %hash = {"1" => "one", "2" => "21,22,23", "3" => "three"} ; 

應該

my %hash = ("1" => "one", "2" => "21,22,23", "3" => "three") ; 

現在來回答您的實際問題,嘗試:

試試這個:

$count=1; 
for %hash.keys.sort -> $key { #no need to sort though 
     # say "$key %hash{$key}"; 
     $count++; 
    } 
print "$count\n"; 
+0

嗨,這是用於Perl5還是Perl6?標量(鍵%hash)似乎不起作用。順便說一下..散列聲明僅用於演示目的,我沒有這樣定義它。我只是把snip fro dd輸出顯示在這裏。我實際上已經將它定義爲你如何在我的真實劇本中展示過。 – User9102d82

+0

你必須在這裏發佈你的代碼,以避免混淆。 – Nagaraju

+0

我已經更新了我的代碼片段(哈希聲明),但它明確提到了「Perl6」。 – User9102d82

3

多虧了IRC Perl 6的聊天社區,這是算不的方式。散列鍵,具有本地/內置功能/方法。

%[email protected]> ./h.p6 
Count is 3 
Count is 3 
%[email protected]> 
%[email protected]> cat h.p6 
#!/usr/bin/perl6 

use v6 ; 

my %hash = (1 => <1 2 3>, 2 => "ljsf", 3 => "AFDS") ; 

say "Count is " ~ +%hash ; 
say "Count is " ~ %hash.elems ; 
%[email protected]> 

謝謝。

+3

我個人喜歡在別人的代碼中看到%hash.elems,這是我必須維護的。 +%很容易錯過,最終會出現一些混亂。 –

+0

@MattOates:可以。我們人類善於錯失東西,而不是錯過.. hehe – User9102d82

2

哈希是Cool,所以你甚至可以避開.elems電話而只使用一個哈希數字:

my %h = :42a, :72b; 
say +%h; # 2 
say "We need {42 + %h} spaces to store stuff"; # We need 44 spaces to store stuff