English 中文(简体)
这个Perl代码把散列推送到数组上有什么问题?
原标题:What s wrong with this Perl code to push a hash onto an array?

我正在尝试制作一个散列数组。这是我的密码。$1、$2等是从正则表达式中匹配的,我已经检查了它们是否存在。

更新:修复了我最初的问题,但现在我遇到了一个问题,即当我将项目推到数组上时,数组的大小没有超过1。。。

更新2:这是一个范围问题,因为@ACL需要在循环之外声明。谢谢大家!

while (<>) {
    chomp;
    my @ACLs = ();

    #Accept ACLs
    if($_ =~ /access-lists+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 . "
";

哈希数组似乎并没有变得更大。

最佳回答

您正在推送不存在的$rule。您打算推送对%rule的引用:

push @ACLs, \%rule;

总是用<code>use strict启动程序;使用警告。这将阻止您尝试推送$rule

更新:在Perl中,数组只能包含标量。构造复杂数据结构的方式是通过具有哈希引用数组。示例:

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

请阅读Perl数据结构食谱

问题回答
my %rule = [...]

push @ACLs, $rule;

这两行引用了两个独立的变量:散列和标量。它们不一样。

这取决于你打算做什么,但有两种解决方案:

push @ACLs, \%rule;

会将引用推入数组。

push @ACLs, %rule;

将各个值(如$key1$0value1$key2$0value2..)推入数组。

您每次通过循环都会清除@ACL。你的我的放错地方了。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签