Avoiding the assumption that hostnames start with "H", and simplifying logic:
#! perl -slw
use strict;
use Data::Dumper;
my( @data, $current );
while( <DATA> ) {
if( my ($host,$ip,$brand) =/^(\w+)\s+(\S+)\s+(\S+)/ ) {
$current and push @data, $current;
$current = {HOST=>$host, IP=>$ip, BRAND=>$brand};
next;
}
my( $key, $val ) = m[\s+(.+)\s+(\S+)$] or next;
$current->{$key} = $val;
}
$current and push @data, $current;
print Dumper \@data;
__DATA__
Hostname1 1.1.1.1 Cisco
Chassis Serial Number xyz123
Interface Gig0/0/31
Hostname2 2.2.2.2 Juniper
Chassis Serial Number abc123
Interface Gi-0/0/31
Output:
$VAR1 = [
{
'Chassis Serial Number' => 'xyz123',
'Interface' => 'Gig0/0/31',
'BRAND' => 'Cisco',
'HOST' => 'Hostname1',
'IP' => '1.1.1.1'
},
{
'HOST' => 'Hostname2',
'BRAND' => 'Juniper',
'Chassis Serial Number' => 'abc123',
'Interface' => 'Gi-0/0/31',
'IP' => '2.2.2.2'
}
];
Alternative, using hostname as a key to a hash:
my ($current,%data)
...
$current and $data{$current->{HOST}} = $current; # in 2 places
$current = {HOST=>$host, IP=>$ip, BRAND=>$brand};
"Software interprets lawyers as damage, and routes around them" - Larry Wall
|