in reply to reading/writing line by line

open (INFILE, "input.txt"); open (OUTFILE, ">output.txt"); while (INFILE) { $_ =~ s/foo/bar/gms; print OUTFILE "$_\n"; }

/m is multi line: not useful when dealing with a single line at a time. /s makes . match newline: not useful if you don't use ..

One liner:

perl -i.backup -pe's/foo/bar/g' filename

Same thing, inside a larger script that you don't want to have using -i all the time:

{ local @ARGV = ('filename'); local $^I = '.backup'; local $_; while (<>) { s/y/yah/g; print; } }

- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.

Replies are listed 'Best First'.
Re: Re: reading/writing line by line
by amarceluk (Beadle) on May 22, 2002 at 18:22 UTC
    I fear this is an especially dumb question, but here goes...

    I've seen a lot of people recommending the "perl -i" solution for regexes, like your
    perl -i.backup -pe 's/foo/bar/g' filename
    Can that be used for multiple regexes in a file? Like, if you wanted to do s/foo/bar/g and s/y/yah/g on the same file?
      I rescind the question. Yes, it's dumb, and yes, I figured it out by doing a search for "perl -i". Sorry.

      Can that be used for multiple regexes in a file? Like, if you wanted to do s/foo/bar/g and s/y/yah/g on the same file?

      Yes. See what happens if you use just perl -pe'undef':

      LINE: while (defined($_ = <ARGV>)) { undef; } continue { die "-p destination: $!\n" unless print $_; }
      So you can just add whatever should be inside the block:
      perl -i -pe's/foo/bar/g; s/y/yah/g;' filename

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

        Thank you! I figured there had to be a way to do it but it wasn't intuitively obvious.