[英]What's wrong with this Perl code to push a hash onto an array?
I'm trying to make an array of hashes. 我正在尝试制作一系列哈希。 This is my code. 这是我的代码。 The $1, $2, etc are matched from a regular expression and I've checked they exist. $ 1,$ 2等与正则表达式匹配,我检查过它们是否存在。
Update: Fixed my initial issue, but now I'm having the problem that my array is not growing beyond a size of 1 when I push items onto it... 更新:修复了我的初始问题,但现在我遇到的问题是,当我将项目推到它上时,我的数组不会超过1的大小......
Update 2: It is a scope issue, as the @ACLs needs to be declared outside the loop. 更新2:这是一个范围问题,因为需要在循环外声明@ACL。 Thanks everyone! 感谢大家!
while (<>) {
chomp;
my @ACLs = ();
#Accept ACLs
if($_ =~ /access-list\s+\d+\s+(deny|permit)\s+(ip|udp|tcp|icmp)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\s+eq (\d+))?/i){
my %rule = (
action => $1,
protocol => $2,
srcip => $3,
srcmask => $4,
destip => $5,
destmask => $6,
);
if($8){
$rule{"port"} = $8;
}
push @ACLs, \%rule;
print "Got an ACL rule. Current number of rules:" . @ACLs . "\n";
The array of hashes doesn't seem to be getting any bigger. 哈希数组似乎没有变得更大。
You are pushing $rule
, which does not exist. 你正在推动$rule
,这是不存在的。 You meant to push a reference to %rule
: 您打算推送对%rule
的引用:
push @ACLs, \%rule;
Always start your programs with use strict; use warnings;
始终use strict; use warnings;
的程序启动您的程序use strict; use warnings;
use strict; use warnings;
. 。 That would have stopped you from trying to push $rule
. 这会阻止你试图推动$rule
。
Update: In Perl, an array can only contain scalars. 更新:在Perl中,数组只能包含标量。 The way complex data structures are constructed is by having an array of hash references. 构造复杂数据结构的方式是通过一个哈希引用数组。 Example: 例:
my %hash0 = ( key0 => 1, key1 => 2 );
my %hash1 = ( key0 => 3, key1 => 4 );
my @array_of_hashes = ( \%hash0, \%hash1 );
# or: = ( { key0 => 1, key1 => 2 }, { key0 => 3, key1 => 4 ] );
print $array_of_hashes[0]{key1}; # prints 2
print $array_of_hashes[1]{key0}; # prints 3
Please read the Perl Data Structures Cookbook . 请阅读Perl Data Structures Cookbook 。
my %rule = [...]
push @ACLs, $rule;
These two lines refer to two separate variables: a hash and a scalar. 这两行指的是两个独立的变量:散列和标量。 They are not the same. 她们不一样。
It depends on what you're waning to do, but there are two solutions: 这取决于你正在做什么,但有两种解决方案:
push @ACLs, \%rule;
would push a reference into the array. 会将引用推送到数组中。
push @ACLs, %rule;
would push the individual values (as in $key1
, $value1
, $key2
, $value2
...) into the array. 将各个值(如$key1
, $value1
, $key2
, $value2
......)推入数组中。
You're clearing @ACLs
each time through the loop. 你每次@ACLs
通过循环清除@ACLs
。 Your my
is misplaced. 你的my
错了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.