簡體   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-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";

哈希數組似乎沒有變得更大。

你正在推動$rule ,這是不存在的。 您打算推送對%rule的引用:

push @ACLs, \%rule;

始終use strict; use warnings;的程序啟動您的程序use strict; use warnings; use strict; use warnings; 這會阻止你試圖推動$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 Data Structures Cookbook

my %rule = [...]

push @ACLs, $rule;

這兩行指的是兩個獨立的變量:散列和標量。 她們不一樣。

這取決於你正在做什么,但有兩種解決方案:

push @ACLs, \%rule;

會將引用推送到數組中。

push @ACLs, %rule;

將各個值(如$key1$value1$key2$value2 ......)推入數組中。

你每次@ACLs通過循環清除@ACLs 你的my錯了。

暫無
暫無

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

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