in reply to Script fails to insert text and appends it towards the end of file.

Why not simply splice the lines from the input file into an array with your output file?

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; } } }

I wasn't sure if you wanted to insert lines starting with BEAM into the output file after the BEAM entries already there but the script above does this. Whatever is in the input file, it adds those to the output file immediately after entries with the same initial 'token'.