13.4. truncate

# Sometimes you need to 
truncate FILEHANDLE, LENGTH;

Example 13-3. examples/files/truncate.pl

#!/usr/bin/perl
use strict;
use warnings;

my $new = $ARGV[0];

my $filename = "file.txt";
open my $fh, "+<", $filename or die "Could not open $!\n";
my $old = <$fh>;

seek $fh, 0, 0;              # move to the beginning of the file 
print $fh $new;
truncate $fh, length $new;   # cut the file to the new size

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed