Truncate typically gets rid of the end of a file. But if you want to delete the first x bytes of a file, there's no trivial way to do it. That's what this snippet does.
sub truncate_front { my $fh = shift; my $pos = shift; my $length = (stat ($fh))[7]; my $buf; my $buf_size = ($pos < 1024 ? $pos : 1024); my $status; if ($pos <= 0) { return ($length); } elsif ($pos >= $length) { truncate ($fh, 0) or die ('truncate: ' . $!); return (0); } $length = 0; while (1) { my $read_pos = $pos + $length; seek ($fh, $read_pos, 0) or die ('seek: ' . $!); $status = read ($fh, $buf, $buf_size); if (!defined ($status)) { die ('read: ' . $!); } elsif ($status == 0) { last; } seek ($fh, $length, 0) or die ('seek: ' . $!); print $fh $buf; $length += $status; } if (defined ($status)) { truncate ($fh, $length) or die ('truncate: ' . $!); } return ($length); }

Replies are listed 'Best First'.
Re: Truncate the front of a file
by jeffa (Bishop) on Dec 21, 2003 at 16:48 UTC
    Too much code. ;)
    perl -pi.bak -e'BEGIN{$/=\1024}($_,$/)=(undef,"\n")if ref$/' file.txt
    Just change 1024 to whatever byte size you want ... you do have to have that much memory available, but the rest is line by line.

    UPDATE:
    merlyn shared a better version in the CB shortly after i posted:

    perl -pi.bak -e'BEGIN{$/=\1024}($_,$/)=()if 1..1' file.txt
    Reading the rest line by line is unecessary. Thanks again merlyn! :)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
•Re: Truncate the front of a file
by merlyn (Sage) on Dec 21, 2003 at 15:41 UTC
    If you have enough memory to read the entire file, this is probably faster:
    { local *ARGV; @ARGV = "yourfilenamehere"; local $/; local $^I = ".bak"; # or "" if you don't want the backup $_ = <ARGV>; # truncate $_ as you wish: it's the entire file print; }
    Note that neither your code nor mine works in a multi-thread/process environment. Not enough flocking. {grin}

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.