Ok, let's try this again, this time with some explanation.

#!/usr/local/bin/perl use warnings; while (<>) { if (/'3'/) { s/^L/(+3) L/g; s/'3'/'3';fac=3/g; s/^/Newline1\n/g; print $_, @h; } elsif (/'2'/) { s/^L/(+2) L/g; s/'2'/'2';fac=2/g; unshift @h, $_; } elsif (/'1'/) { s/^L/(+1) L/g; s/'1'/'1';fac=1/g; unshift @h, $_; } elsif (/Line5/) { print $_, "MeanLine\n"; } else { print; } } __END__

Here, @h is an array variable global to the program. I use it instead of the hold space of sed. This array starts empty. When I meet the lines with '1' or '2', unshift inserts them to the beginning of the array. Note that I've moved the print statement in the else part of the if, so that it won't print these lines immediately. Now, when the script reads the line '3', it will first print the line itself (with Newline prepended), and then it will print the contents of the array @h. At that time @h has the lines with '2' as the first element and the one with '1' as the second.

Update: it might have been better if I used next instead of moving the print in the conditional. That would not only make the code more similar to a sed script, but would avoid some repetitions too. I would not change it now, however.


In reply to Re: sed to perl conversion revisted by ambrus
in thread sed to perl conversion revisted by NovMonk

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.