What is wrong with this Perl code to push a hash to an array?

I am trying to create an array of hashes. This is my code. $ 1, $ 2, etc. Match with regex and I checked that they exist.

Update: My original problem was fixed, but now I have a problem with my array not exceeding size 1 when I click on it with elements ...

Update 2: This is a scope issue, since @ACL needs to be declared outside the loop. 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 hash array doesn't seem to get bigger.

+3
source share
3 answers

You click $rulethat does not exist. You would like to send a link to %rule:

push @ACLs, \%rule;

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.

+6
my %rule = [...]

push @ACLs, $rule;

: . .

, , :

push @ACLs, \%rule;

.

push @ACLs, %rule;

( $key1, $value1, $key2, $value2...) .

+2

You clean @ACLsevery time through a cycle. Yours is myinappropriate.

+2
source

Source: https://habr.com/ru/post/1791890/


All Articles