简体   繁体   中英

Perl: Load data by row

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM