in reply to Create based on repeating data

Like this?:

#! perl -slw use strict; use Data::Dump qw[ pp ]; my( %data, %subhash, $last ); while( <DATA> ) { if( /^H/ ) { if( $last ) { $data{ $last } = { %subhash }; undef %subhash; } ( $last, my( $key, $val ) ) = m[(\S+)\s+(.+)\s+(\S+)$]; $subhash{ $key } = $val; } else { my( $key, $val ) = m[^\s+(.+)\s+(\S+)$]; $subhash{ $key } = $val; } } $data{ $last } = { %subhash }; pp \%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

Outputs:

C:\test>1170268.pl { 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", }, }

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: Create based on repeating data
by NetWallah (Canon) on Aug 24, 2016 at 03:21 UTC
    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