use strict; my $infile = 'input.txt'; my $otfile = 'output.txt'; my $token; our @outfile; # Read existing output file into array open my $ot, '<', $otfile or die "$otfile: $!\n"; while (<$ot>) { push @outfile, $_; } close $ot; # Iterate over input file appending rows to array open my $in, '<', $infile or die "$infile: $!\n"; while (<$in>) { (undef, $token, undef) = split /\W/, $_; &insert($token, $_) if $token; } close $in; # Replace output file eliminating blank lines open $ot, '>', $otfile or die "$otfile: $!\n"; foreach my $line(@outfile) { print $ot $line if $line !~ /^ ?\n/; } exit 0; # Insert the line into @outfile at the correct place sub insert { my $token; my $flag = 0; for (my $i; $i < @outfile; $i++) { (undef, $token, undef) = split /\W/, $outfile[$i]; $flag = 1 if $token eq $_[0]; if ($flag and $token ne $_[0]) { print "$_[0]\n"; splice @outfile, $i, 0, $_[1]; $flag = 0; } } }