in reply to Re^2: File Read
in thread File Read

My question becomes... How can I Open a file once, read the contents of the file then Truncate these contents to another value and then close the file?

Replies are listed 'Best First'.
Re^4: File Read
by Fletch (Bishop) on Mar 12, 2007 at 14:03 UTC

    You'd probably use sysopen with seek and truncate, but that's probably still not what you really want to do. Read the entries in perlfaq5 on file locking and flock if you want to do this correctly.

Re^4: File Read
by diotalevi (Canon) on Mar 12, 2007 at 16:21 UTC

    Here's an example.

    use POSIX qw( LOCK_EX SEEK_SET ); # Open a shared file for reading and writing open my $fh, '<+', $filename or die "Can't open $filename for reading: $!"; flock $fh, LOCK_EX | LOCK_NB or die "Can't get an exclusive lock on $filename: $!"; # Read one line. my $contents = <$fh>; # Empty the file. seek $fh, 0, SEEK_SET or die "Can't seek to the start of $filename: $!"; truncate $fh, 0 or die "Can't truncate $filename: $!"; # Put something new in there. print $fh "...." or die "Can't write to $filename: $!"; close $fh or die "Can't write to $filename: $!";

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊