in reply to Re^4: adding lines at specific addresses
in thread adding lines at specific addresses
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:
So, does it really need to be any more complicated than that?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).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: adding lines at specific addresses
by pindar (Initiate) on Oct 12, 2005 at 06:29 UTC | |
by graff (Chancellor) on Oct 12, 2005 at 06:56 UTC | |
by pindar (Initiate) on Oct 13, 2005 at 11:19 UTC |