Perl: Load data by row

2019-09-04 07:43发布

问题:

I'm continuing my Perl learning.

In this case I'm trying to load data from .txt file into array. My script generates netstat output which looks like this:

Proto Recv-Q Send-Q Local Address    Foreign Address         State       PID/Program name
tcp     0      0 0.0.0.0:3790        0.0.0.0:*               LISTEN      7550/nginx.conf 
tcp     0      0 127.0.1.1:53        0.0.0.0:*               LISTEN      1271/dnsmasq    
tcp     0      0 127.0.0.1:631       0.0.0.0:*               LISTEN      24202/cupsd 

Next step in process is to put data which is loaded from file into array and then in hash, making it sortable by rows, for example sorting output to find out all information which belongs specific port number.

My question is: What is proper way to load this data into array and then hash to make it accessible and sortable for the output?

回答1:

I think you need AoH (array of hashes). After that you can get everything you want with custom sort:

my @records = [
 { Proto => "tcp", 'Recv-Q' => 0, ..., 'Local Address' => "0.0.0.0:3790", ..., State => "Listen", ... },
 { Proto => "tcp", 'Recv-Q' => 0, ..., 'Local Address' => "127.0.1.1:53", ..., State => "Listen", ... },
 { Proto => "tcp", 'Recv-Q' => 0, ..., 'Local Address' => "127.0.0.1:631", ..., State => "Listen", ... },
];

my @records_sorted_by_state = sort { $a->{State} cmp $b->{State} } @records;