in reply to seek in a text file

truncate + tell

Update: Code:

#!/bin/perl -w use strict; my $file="dogy"; open(FH, "+<$file"); flock(FH, 2); my @newEntries; while(my $line = <FH>) { chomp($line); if ($line%2==1) { next; } push(@newEntries,$line); } seek FH,0,0; foreach my $ent (@newEntries) { print FH $ent . "\n"; } truncate FH, tell FH; close(FH)

Update: Even better?

#!/bin/perl -w use strict; my $file="dogy"; open(FH, "+<$file"); flock(FH, 2); my @newEntries; while(my $line = <FH>) { chomp($line); if ($line%2==1) { next; } push(@newEntries,$line); } seek FH,0,0; truncate FH, 0; foreach my $ent (@newEntries) { print FH $ent . "\n"; } close(FH)

Replies are listed 'Best First'.
Re^2: seek in a text file
by jwkrahn (Abbot) on Oct 06, 2008 at 04:45 UTC

    Or even better?

    #!/usr/bin/perl use warnings; use strict; use Fcntl qw/ :seek :flock /; my $file = 'dogy'; open my $FH, '+<', $file or die "Cannot open '$file' $!"; flock $FH, LOCK_EX or die "Cannot flock '$file' $!"; my @newEntries = grep !($_ % 2), <$FH>; seek $FH, 0, SEEK_SET or die "Cannot seek '$file' $!"; truncate $FH, 0 or die "Cannot truncate '$file' $!"; print $FH @newEntries; close $FH;
Re^2: seek in a text file
by catfood (Novice) on Oct 06, 2008 at 01:18 UTC
    works good, thanks.