Timothy Johnson wrote:
> Except that it will essentially create a new file.  Why did you want
> to avoid writing a new file?  As far as I know, you can't just
> "erase" data in the middle of a file.  That's just not how they work.
> Someone correct me if I'm wrong.  As far as I know, any program that
> does this rewrites the file. The only thing that is somewhat similar
> is that you can do a sysread and change part of a file, but I don't
> think you can remove part of a file without rewriting it. 

You are correct. The only way to remove data from the middle of a file is to
rewrite the remainder of the file starting from the point of removal. 

You can remove the blank lines 'in-place' without writing to a second file
(which is what Perl's -i does), but you have to do some file pointer
manipulation. Here's an example:

    #!/usr/bin/perl

    use strict;
    use Fcntl qw(:seek);

    squeeze(shift @ARGV) while @ARGV;

    sub squeeze {
        my $fname = shift;

        open F, "+<$fname" or die "Couldn't open $fname: $!\n";
        my ($p1, $p2);
        $p1 = $p2 = tell(F);
        while (<F>) {
            $p2 = tell(F);
            next if /^$/;
            seek(F, $p1, SEEK_SET);
            print F $_;
            $p1 = tell(F);
            seek(F, $p2, SEEK_SET);
        }
        truncate(F, $p1);
        close(F);
    }

Frankly, the one-liner with perl -i is much preferred.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to