简体   繁体   English

在Perl中迭代哈希数组

[英]Iterate an array of hashes in perl

I was iterating through all the entries of a dictionary source file, for each entry I use one hash to store some relations between the headword (only one headword per entry; as the value of a hash ) and its corresponding topic (maybe there're more than one topic s in one entry; as the key of a hash ), and after iterating through each entry I add the hash into an array and put all hash es together in that array by the end of all iteration, then I'm gonna do something with that array of hash es. 我是通过字典源文件的所有条目,每个条目我使用一个迭代hash存储之间的一些关系, headword (只有一个headword每个条目;作为value一的hash )及其相应的topic (也许有很一个条目中有多个topic ;作为hashkey ),并且在遍历每个条目之后,我将hash添加到array ,并在所有迭代结束时将所有hash es放到该数组中,然后将使用该hash array做某事。

Note:Different hash es may contain the same key , so I can't convert the all hash es to an array and then convert them back to one single hash , that will erase the duplicate key s. 注意:不同的hash es可能包含相同的key ,因此我无法将所有hash es转换为array ,然后再将它们转换回单个hash ,这将删除重复的key s。

I get the following error upon run the code: 运行代码时出现以下错误:

Can't use string ("art") as a HASH ref while "strict refs" in use at this line: while (my ($key, $value) = each %{$hash_ref}){ 在此行使用“严格引用”时,不能将字符串(“ art”)用作HASH引用: while (my ($key, $value) = each %{$hash_ref}){

"art" is one of the topics mentioned above. “艺术”是上述主题之一。

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

use feature ':all';
my $filename='a';
use Data::Dumper qw(Dumper);
open(DICT, "<", $filename)
    or die "Cannot open '$filename': $!";

my @array;    

while(<DICT>){
    my %h;
    my $hw=$1  if /(^.*?)(?=<link rel)/;
    while (m/\<SUBJECT\-AREA\>(.*?)\<\/SUBJECT\-AREA\>/g) {
        $h{$1}=$hw;
    }

    push(@array, %h);

    END {
        for my $hash_ref (@array){
            while (my ($key, $value) = each %{$hash_ref}){
                print "$key\n\@\@\@LINK=$value\n</>\n";
            }
        }
    }
}

Your problem is that you don't have an array full of hashes (hash references) to iterate over. 您的问题是您没有足够的散列(哈希引用)数组来进行迭代。 When you do 当你做

 push(@array, %h);

it is flattening %h into a list of key/value pairs and pushing that list onto the end of @array . 它会将%h平为键/值对列表,并将该列表推到@array的末尾。

What you meant to do instead was 你本来打算做的是

push @array, \%h;

which pushes a reference to %h onto @array . 这会将对%h的引用推到@array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM