in reply to Re: Matching Question
in thread Matching Question

OK, that worked, but how do I write it back to the same file?
Bobby

Replies are listed 'Best First'.
Re: Re: Re: Matching Question
by thelenm (Vicar) on Sep 20, 2002 at 19:02 UTC
    Hmmm... if this is the entire script, you could simply pass the filename as a parameter and use the -p and -i switches, something like this:
    #/usr/bin/perl -pi.bak $count++ if s/^go/\//; END { print STDERR "There were $count lines starting with 'go' in the +file\n"; }
    This will automatically overwrite your original file with the new, substituted lines. It will also create a backup file named "<file>.bak" just in case. :-)

    If this is not your entire program, then you can just capture its output to a new file, then rename the new file to have the same name as the old one. You could have your program do this itself by printing its output to a new file, then renaming that file. Maybe something like this (this is not the whole program, of course):

    open FILE, "< $file" or die "Can't open input file: $!\n"; open OUT, "> '$file.new'" or die "Can't open output file: $!\n"; while (<FILE>) { $count++ if s/^go/\//; print OUT; } close OUT; close FILE; print STDERR "There were $count lines starting with 'go' in the file\n +"; rename $file, "$file.bak"; # make backup copy rename "$file.new", $file; # overwrite original file

    -- Mike

    --
    just,my${.02}