in reply to [Perl 5.26][Linux LEAP] Array/List/Hash misunderstanding

I solved the issue like this:
foreach my $key (keys %hashEntries) { my @temp=$hashEntries{$key}; #print "Elements: ".@temp."\t"; print "[After no dump] Test 2 $key ->\t"; foreach my $element (@temp) { if($element ~~ /ARRAY/) { print "Array détecté...\t"; foreach my $autreelement (@$element) { print "[@$autreelement]\n"; $lesdomaines.="@$autreelement"; $lesdomaines.="\t"; } } else { print "[@$element]\n"; $lesdomaines.="@$element"; $lesdomaines.="\t"; } } print $key."\t".$lesdomaines."\n"; $lesdomaines=""; }
output here

Replies are listed 'Best First'.
Re^2: [Perl 5.26][Linux LEAP] Array/List/Hash misunderstanding
by ikegami (Patriarch) on Feb 15, 2023 at 06:43 UTC

    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.