如何在 perl 中推送或追加一个哈希到一个多维哈希上?

问题描述 投票:0回答:1

下面的代码创建了一个多维哈希的哈希值,如果这句话是正确的话。(还有更好的描述吗?)

每个新的子哈希的 $CRIT{sourcefile}{raw}是由4行代码创建的。(该 chunk 子哈希只是为了提醒大家,在这个数组中还会有其他几个哈希值)。)

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper qw(Dumper);
my $index=0;
my %CRIT;
$CRIT{chunk}{raw}{1}{ANDOR} = 'ORNOT';
$index++;
$CRIT{sourcefile}{raw}{$index}{ANDOR} = 'OR';
$CRIT{sourcefile}{raw}{$index}{regex} = 'Woody\s+Guthrie';
$CRIT{sourcefile}{raw}{$index}{mod} = '';
$index++;
$CRIT{sourcefile}{raw}{$index}{ANDOR} = 'ANDNOT';
$CRIT{sourcefile}{raw}{$index}{regex} = '((Seeger)|(Baez))';
$CRIT{sourcefile}{raw}{$index}{mod} = 'i';
print Dumper \%CRIT;
my %NOWhash;
%NOWhash = (
   'ANDOR' => 'OR',
   'regex' => '\bUtah\s*Phill?ips\b',
   'mod' => 'i',
);
print Dumper \%NOWhash;

但是考虑到 %NOWhash,在底部创建。有什么方法可以 push%NOWhash$CRIT{sourcefile}{raw}? 如果有,有没有办法指定一个特定的? $index 到它?

perl multidimensional-array hash push
1个回答
1
投票

当一个人有一个项目序列时,数组通常是最合适的结构。

my %CRIT;
$CRIT{chunk}{raw} = [
   {
      ANDOR => 'ORNOT',
   },
   {
      ANDOR => 'OR',
      regex => 'Woody\s+Guthrie',
      mod   => '',
   },
   {
      ANDOR => 'ANDNOT',
      regex => '((Seeger)|(Baez))',
      mod   => 'i',
   },
];

push @{ $CRIT{chunk}{raw} }, {
   ANDOR => 'OR',
   regex => '\bUtah\s*Phill?ips\b',
   mod   => 'i',
);

参见:

© www.soinside.com 2019 - 2024. All rights reserved.