Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

How do I save changes made to a file

by Anonymous Monk
on Mar 28, 2000 at 21:54 UTC ( [id://6339]=perlquestion: print w/replies, xml ) Need Help??

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

I have a file and I need to comment out two lines.After commenting them out I need to save the changes . Need Help ASAP Thanks and Have a perl day

Replies are listed 'Best First'.
Re: How do I save changes made to a file
by devslashneil (Friar) on Jun 18, 2003 at 04:24 UTC
    Tie::File could be used to automatically save changes to the file. This is also useful if the file isn't small enough to fit into memory all at once.

    #!/usr/bin/perl use Tie::File; my $filename = 'foo.dat'; tie @array, 'Tie::File', $filename or die "Cannot open $filename\n"; $array[2] = '#'.$array[2]; $array[3] = '#'.$array[3];

    This will comment out lines 3 and 4 in the file "foo.dat" and automatically save changes.

    - Neil
Re: How do I save changes made to a file
by chromatic (Archbishop) on Mar 28, 2000 at 22:48 UTC
    Simply open the file for writing (not appending) and write out the entire file. This is the easiest way to do it:
    # file opened, read into $my_data, closed, and $my_data modified appro +priately { local *OUTPUT; open(OUTPUT, "> filename_here") || die "Can't open output file: $! +"; print OUTPUT $my_data; close(OUTPUT) || die "Can't close my file: $!"; }
    A few comments. The curly braces give us a block scope for the local filehandle OUTPUT. If OUTPUT is defined with a global scope elsewhere in the program (as it may be in the future), we don't want to clobber it, so local within a block is a good idea.

    Next, we open that filehandle to write (that's what the angle brace is for) to the filename. If that doesn't work, we print an error message using the special variable $! (which holds the error message from the failed open call).

    After that, we print to the filehandle. No big deal there. Finally, we close the filehandle and again print an error message if it fails. That's the end of the block.

    This is by far the easiest way to save changes to a file. Other options include using sysread and syswrite or using append mode (">> filename_here"), but if your file is small enough to fit into memory all at once, just do it this way.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://6339]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 16:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found