JojoLinkyBob has asked for the wisdom of the Perl Monks concerning the following question:

How can I change the following code so that the #do stuff block will run against any new lines that the search n replace will create. My current workaround to this is to read the file in, search and replace (to create new lines), close the filehandle, reopen it, and now the the new lines that were created before are on all separate lines?
while(<fp>) { s/\(/\n\(\n/g; s/\)/\n\)\n/g; #do stuff to current line }

thx, Desert coder

Replies are listed 'Best First'.
Re: When One Line Becomes Three
by Masem (Monsignor) on Jun 14, 2001 at 22:07 UTC
    You could do this:
    while(<fp>) { s/\(/\n\(\n/g; s/\)/\n\)\n/g; my $line = join "\n", map { # do stuff to individual line at $_ } split /\n/, $_; # save line to array, possibly? }

    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: When One Line Becomes Three
by marcink (Monk) on Jun 14, 2001 at 22:08 UTC
    Just split the results to process them in another loop:

    while (<fp>) { s/\(/\n\(\n/g; s/\)/\n\)\n/g; #do stuff to current line print ">$_<\n" foreach split /\n/; # OR foreach my $t ( split /\n/ ) { print ">$t<\n"; } }


    -mk
      Thanks, the response were helpful. After farting around with it some more, I came up with
      my @lines = split (/\n/); for my $line(@lines) {
      which is pretty much your implementation. Thanks! Desert coder
(tye)Re: When One Line Becomes Three
by tye (Sage) on Jun 15, 2001 at 02:06 UTC

    Minor improvements to the regexes:

    while(<fp>) { s#([()])#\n$1\n/g; for( split /(?<=\n)/ ) { print "Look Ma, still got newlines: $_"; } }

            - tye (but my friends call me "Tye")
Re: When One Line Becomes Three
by dragonchild (Archbishop) on Jun 14, 2001 at 21:59 UTC
    I would do something like:

    open IN_FILE, "<$filename" or die "Cannot open $filename for reading\n +"; my @file = <IN_FILE>; close IN_FILE; for (my $i = 0; $i < $#file; $i++) { # Do your stuff here. # If you end up changing the number of lines, back up $i and # go through indices again. }

    Warning: You actually have to think through your algorithm and figure out all the possibilities and not just code off the cuff like most of us are used to doing. (Heavens forfend! I have to think?!?)