my @devices; open (FILE,"config.txt") or die "cannot open file : $!"; # Always put a label on your loop when using next CONFIG_LOOP: while ( my $line = ) { # Never use $_ directly if ( $line =~ /^(\w+)\s+/ ) { # Adding to the array push( @devices, "$1 => " ); } elsif ( $line =~ (/inet\saddr:(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/) ) { # Adding the IP address to the last known device $devices[-1] .= "$1.$2.$3.$4\n"; } else { # Skipping other lines next CONFIG_LOOP; } } close (FILE); foreach my $device ( @devices ) { print $device; }