簡體   English   中英

Perl哈希麻煩

[英]Perl Hash Trouble

Perl專家的簡單入門...

我想要一個僅接收項目數組(實際上是多個數組)並計算哈希鍵區中每個項目存在的次數的函數。 但是,我真的不確定Perl哈希。

@array = qw/banana apple orange apple orange apple pear/

我讀到您需要使用類似以下代碼的數組:

my %hash = (
    'banana' => 0,
    'orange' => 0,
    'apple' => 0
    #I intentionally left out pear... I only want the values in the array...
);

但是,我正在努力使一個循環起作用,該循環可以遍歷該循環,並使用與數組中每個值相等的對應鍵將一個值添加到該值。

foreach $fruit (@array) {
    if ($_ #is equal to a key in the hash) {
        #Add one to the corresponding value
    }
}

它具有幾個基本功能,它們全部包裝在一起,因此,代表所有入門的Perl程序員,在此先謝謝您!

所有你需要的是

my @array = qw/banana apple orange apple orange apple pear/;
my %counts;
++$counts{$_} for @array;

這導致像

my %counts = ( apple => 3, banana => 1, orange => 2, pear => 1 )

如果願意,可以使用塊和顯式循環計數器變量編寫for循環,如下所示

for my $word (@array) {
  ++$counts{$word};
}

具有完全相同的效果。

您可以使用exists

http://perldoc.perl.org/functions/exists.html

給定一個指定哈希元素的表達式,即使哈希中的指定元素曾經被初始化,即使相應的值未定義,也返回true。

foreach my $fruit (@array) {
    if (exists $hash{$fruit}) {
        $hash{$fruit}++;
    }
}

假設您有一個名為@array 您將使用$array[0]訪問數組的第0個元素。

哈希值相似。 %hash的banana元素可以通過$hash{'banana'}

這是一個非常簡單的示例。 它利用了隱式變量$_和一些字符串插值:

use strict;

my @array = qw/banana apple orange apple orange apple pear/;

my %hash;
$hash{$_} += 1 for @array;              #add one for each fruit in the list
print "$_: $hash{$_}\n" for keys %hash; #print our results

如果需要,您可以檢查是否存在特定的哈希鍵: if (exists $hash{'banana'}) {...}

您最終會看到稱為“ hashref”的東西,它不是哈希,而是哈希的引用 在這種情況下, $hashref具有$hashref->{'banana'}

我想在這里了解您:

  1. 您有一個數組和一個哈希。
  2. 您想要計算數組中的項目並查看它們發生了多少時間
  3. 但是,僅當此項目在您的哈希中。

將哈希視為鍵控數組。 數組有位置。 您可以談論第0個元素或第5個元素。 只有一個第0個元素,而它們只有一個第5個元素。

讓我們看一下哈希:

my %jobs;
$jobs{bob} = "banker";
$jobs{sue} = "banker";
$jobs{joe} = "plumber;

正如我們可以在數組的第0位討論元素一樣,我們也可以使用bob的元素討論元素。 就像在第0位只有一個元素一樣,只有一個帶有bob鍵的元素。

哈希提供了一種快速查找信息的方法。 例如,我可以快速找到Sue的工作:

print "Sue is a $jobs{sue}\n";

我們有:

  • 充滿項目的數組。
  • 包含我們要計算的項目的哈希
  • 另一個與總數的哈希值。

這是代碼:

use strict;
use warnings;
use feature qw(say);

my @items       = qw(.....);   # Items we want to count
my %valid_items =   (....);    # The valid items we want

# Initializing the totals. Explained below...
my %totals;
map { $totals{$_} = 0; } keys %valid_items;

for my $item ( @items ) {
    if ( exists $valid_items{$item} ) {
        $totals{$item} += 1;  #Add one to the total number of items
    }
}

#
# Now print the totals
#
for my $item ( sort keys %totals ) {
    printf "%-10.10s  %4d\n", $item, $totals{$item};
}

map命令獲取右側的項目列表 (在本例中為keys %valid_items ),並遍歷整個列表。

從而:

map { $totals{$_} = 0; } keys %valid_items;

簡短地說:

for(鍵%valid_items){$ totals {$ _} = 0; }

我使用的其他東西是 ,這些鍵將哈希的所有鍵作為數組(好的列表)返回。 因此,當我說keys %valid_items時,我得到了applebananaoranges

[exists](http://perldoc.perl.org/functions/exists.html) is a test to see if a particular key is in my hash. The value of that key might be zero, a null string, or even an undefined value, but if the key is in my hash, the [exists](http://perldoc.perl.org/functions/exists.html) is a test to see if a particular key is in my hash. The value of that key might be zero, a null string, or even an undefined value, but if the key is in my hash, the existing函數將返回一個真值。

但是,如果我們可以用exists ,看是否有關鍵的是在我的%valid_items哈希值,我們可以做同樣的%totals 它們具有相同的鍵集。

相反,或者創建%valid_items哈希,我將使用@valid_items數組,因為數組@valid_items更易於初始化。 我只需要列出這些值。 我可以使用@valid_items來代替使用keys %valid_items獲取鍵列表:

use strict;
use warnings;
use feature qw(say);

my @items = qw(banana apple orange apple orange apple pear);   # Items we want to count
my @valid_items = qw(banana apple orange);    # The valid items we want

my %totals;
map { $totals{$_} = 0; } @valid_items;

# Now %totals is storing our totals and is the list of valid items

for my $item ( @items ) {
    if ( exists $totals{$item} ) {
        $totals{$item} += 1;  #Add one to the total number of items
    }
}

#
# Now print the totals
#
for my $item ( sort keys %totals ) {
    printf "%-10.10s  %4d\n", $item, $totals{$item};
}

並輸出:

apple          3
banana         1
orange         2

我喜歡使用printf來使表保持井井有條。

這將更容易理解,因為兩個月前我也開始編寫代碼。

use Data::Dumper;
use strict;
use warnings;
my @array = qw/banana apple orange apple orange apple pear/;

my %hashvar;
foreach my $element (@array) {
    #Check whether the element is already added into hash ; if yes increment; else add. 
    if (defined $hashvar{$element}) {  
        $hashvar{$element}++;
    }
    else {
        $hashvar{$element} = 1;

    }

}
print Dumper(\%hashvar);

將輸出輸出為$ VAR1 = {'banana'=> 1,'apple'=> 3,'orange'=> 2,'pear'=> 1}; 干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM