in reply to Re: opening file for editing
in thread opening file for editing

I wont be able to do it using perl one liner what i want is open an already existing file search for a pattern replace it with something else on the fly i dont want any temp files to be created

Replies are listed 'Best First'.
Re^3: opening file for editing
by clueless newbie (Curate) on Oct 09, 2011 at 14:22 UTC
    Just For Fun: ... to update a file "in place".
    ... open(my $READER,'+<',$Filename_S) or die "Can't open '$Filename_S'! $!"; open(my $WRITER,'+<',$Filename_S) # Don't use + '+>' or die "Can't open '$Filename_S'! $!"; # The overflow buffer: my @Buffer_a; while (<$READER>) { # Read (past tense) a line - buffer its replacement ... # Modify the line here! my $Update_s=... push(@Buffer_a,$Update_s); # Write from the overflow buffer if we can ... while (@Buffer_a && length($Buffer_a[0]) < tell($READER)-tell( +$WRITER)) { # Enough room to write $Buffer_a[0] so write it ... print $WRITER shift(@Buffer_a); }; }; # Nothing more to read ... close($READER) or die "Can't close '$Filename_S'! $!"; # If there's anything in the buffer write it ... while (@Buffer_a) { print $WRITER shift(@Buffer_a); }; # Truncate the file, in case, what we're writing is shorter than w +hat we read truncate($WRITER,tell($WRITER)); # ... and close close($WRITER) or die "Can't close '$Filename_S'! $!"; ...
    Be aware that if something should happen during the update one may be "up the creek without a paddle".
Re^3: opening file for editing
by pvaldes (Chaplain) on Oct 09, 2011 at 09:08 UTC

    you can do this in two steps:

    read open dump all to a variable (in memory) apply a substitution to this variable close re-open the file, now for writing print the changed variable to the file (overwrite the whole file) and close again

    No temp files here, and your file is updated as you want. Use perldoc for the details.

      oh well, this seems to be more straightforward solution, thats fine..but can this be done by opening file only once

        1. Monks have mentioned the documentation for open
        2. Monks provided hyperlinks to the documentation for open
        3. Monk specifically mentioned the +< and +> operators

        Did you read it?

Re^3: opening file for editing
by choroba (Cardinal) on Oct 09, 2011 at 08:16 UTC
    Then you'll have to switch to Microsoft Word ™.
      so its not possible using perl
        You specified "no oneliners" and "no temp files". You have not specified what you are going to replace with what nor how big your file is. Under these conditions, I see no general solution (MS Word might use temp files, too, did you know?)