while () { if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)/) { my $a = $1; my $b = $2; my $c = $3; my $d = $4; my $ip = "$a.$b.$c.$d"; my $classc = "$a.$b.$c"; my $classb = "$a.$b"; my $classa = "$a"; push(@{$hash{$classa}{$classb}{$classc}}, $ip); } } for my $a ( keys %hash ) { for my $b ( keys %{$hash{$a}} ) { for my $c ( keys %{$hash{$a}{$b}} ) { for my $ip ( @{$hash{$a}{$b}{$c}} ) { print "$ip\n"; } } } } use Data::Dumper; print Dumper \%hash;