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'.


In reply to Re: Script fails to insert text and appends it towards the end of file. by Bod
in thread Script fails to insert text and appends it towards the end of file. by always_coys

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.