Well, on the whole, that's not so bad... But if you are creating 256 copies of that "if ... else ..." block, one for each possible numeric following "LABEL O", then you really have missed some important points about programming in general (understanding loops and variables) and about perl in particular (using regular expressions).

For that matter, I think the regular expression you've shown is probably not what you really want -- try putting square brackets around the "\n." -- and don't forget to include $3 when you print stuff out.

You also want to meet a new friend: $/ also known as "$INPUT_RECORD_SEPARATOR" (look for a description of it here: perlvar -- it's about a quarter of the way down). Based on this new information you've shown, it looks like the input data is structured in blocks, where each block ends with "(STOP)\n". You can tell perl to use that string and the end-of-record marker, instead of the default "\n", and simplify your code immensely:

open( IN, "some_file.tex" ) or die $!; { local $/ = "(STOP)\n"; my $expected_id = 1; while (<IN>) { # read a whole block up to "(STOP)\n" if ( s/\(LABEL O $expected_id\)\n/$1 NEWSTUFF/ ) { print; # all done with this block } else { print "(LABEL O $expected_id)\n NEWSTUFF\n(STOP)\n"; # add a new block } my $expected_id++; } } # closing this block drops the local value of $/ # now $/ is back to it's default value (in case you # have to read other stuff in the normal fashion).
So, does it really need to be any more complicated than that?

In reply to Re^5: adding lines at specific addresses by graff
in thread adding lines at specific addresses by pindar

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.