in reply to Re: [Perl 5.26][Linux LEAP] Array/List/Hash misunderstanding
in thread [Perl 5.26][Linux LEAP] Array/List/Hash misunderstanding
This is not a good solution. This is quite a poor solution. You shouldn't be checking if the value is an array reference. It should always be an array reference.
use List::Util qw( uniq ); use Sort::Natural qw( natsort ); my %data; while ( <$fh> ) { chomp; my ( $ip, @hosts ) = split; push @{ $data{ $ip } }, @hosts; } for my $ip ( natsort keys( %data ) ) { my @hosts = natsort uniq @{ $data{ $ip } }; say join "\t", $ip, @hosts; }
Actually, I'd use a hash of hashes since it will handle duplicates. The code would look something like this:
use Sort::Natural qw( natsort ); my %data; while ( <$fh> ) { chomp; my ( $ip, @hosts ) = split; ++$data{ $ip }{ $_ } for @hosts; } for my $ip ( natsort keys( %data ) ) { my @hosts = natsort keys %{ $data{ $ip } }; say join "\t", $ip, @hosts; }
It needs to handle blank lines and comments, but you get the idea.
You don't need to use natsort, but it provides a better sort order than sort. In fact, you don't have to use any sorting at all, but it's nicer.
|
|---|