in reply to Generation of Array of hashes by reading a file

Doing a two step via flag is not needed

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; ################ my @AoH; my $rec; open my $fh, '<', 'interface.txt' or die; while (<$fh>) { chomp; if (/^(\w+\d{1}):\s+flags=(.*?>)/) { $rec = {}; push @AoH, $rec; $rec->{'interface'} = $1; $rec->{'flags'} = $2; } elsif (/ether\s+(.*$)/) { $rec->{'ether'} = $1; } elsif (/media:\s+(\w+)/) { $rec->{'media'} = $1; } elsif (/inet\s+(\w+\.\w+\.\w+\.\w+)/) { $rec->{'inet'} = $1; } elsif (/status: (\w+)/) { $rec->{'status'} = $1; } } close($fh); print Dumper \@AoH;

Replies are listed 'Best First'.
Re^2: Generation of Array of hashes by reading a file
by NetWallah (Canon) on Jan 04, 2018 at 21:27 UTC
    Slightly shorter loop:
    # After "open" .. my %wanted = map {$_=>1} qw|media inet status ether|; while (<$fh>) { chomp; if (/^(\w+\d{1}):\s+flags=(.*?>)/) { $rec = {}; push @AoH, $rec; $rec->{'interface'} = $1; $rec->{'flags'} = $2; next; } if (/(\w+):?\s+(.*$)/ and $wanted{$1}) { $rec->{$1} = $2; } }

                    We're living in a golden age. All you need is gold. -- D.W. Robertson.

Re^2: Generation of Array of hashes by reading a file
by pr33 (Scribe) on Jan 04, 2018 at 21:58 UTC

    Thanks Huck and other Monks. All the solutions work. One of the doubt I had with this, Every time when the line matches the key related to interface, we are making the hash empty and then pushing that on to Array. I was assuming the Array will only contain a list of empty hashes, But not the case when I run the script with your solution. Can you please explain or help me understand the push statement after assigning empty hash to rec

      $rec is not a hash, it's a hash reference. When you change the referenced hash, all references pointing to it see the new value.

      my $hash_ref = {}; push my @arr, $hash_ref; $hash_ref->{key} = 'value'; print $arr[0]{key}; # value

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

        Thanks Choroba. That cleared my confusion around this.