in reply to begining of a file

Depends on how big and what format you require.

One way is to put the contents of the file into an array, write your first line(s), then spit the array afterward. Example (yeah I'm skipping strict, warnings, errorcodes, and other good programming practices):

open (GB,"$bookfile"); @oldstuff = <GB>; close GB; open (FILE,">$newfile"); print FILE "pre-pendings here\n"; print FILE "@oldstuff"; close FILE; # rename file if necessary

Another way is to write your pre-pending content to a file, then stream (is this the right word) the old file contents. In other words:

open (FILE,">$newfile"); print FILE "pre-pendings here\n"; open (GB,"$bookfile"); while (<GB>) { print FILE "$_"; } close GB; close FILE; # rename file if necessary

Replies are listed 'Best First'.
Re: Re: begining of a file
by clintp (Curate) on Aug 21, 2001 at 19:11 UTC
    Yet another way is to cheese together a tied filehandle that simply prepends whatever you write onto the beginning of the file. Kinda like what you're doing, but with a simpler interface.
    package Beginning; use Fcntl; sub TIEHANDLE { my($class)=@_; return bless { fh=> undef }, $class; } sub OPEN { my($self)=shift; return sysopen($self->{fh}, $_[0], O_RDWR | O_CREAT, 0666); } sub CLOSE { close($_[0]->{fh}) if ($_[0]->{fh}); $_[0]->{fh}=undef; } sub PRINT { my($self,$len)=shift; local $/; $_=$self->{fh}; seek $_, 0, 0 or warn "$!"; my $buf=<$_>; seek $_, 0, 0 or warn "$!"; print $_ @_; print $_ $buf; }
    Then to use it just:
    tie *FH, "Beginning"; open(FH, "Hello"); # This will actually be read/write print FH "Look ma, I'm first", scalar(localtime), "\n"; close(FH);
    It's incomplete and not scalable, just something to think about. A fun modification might be to have the PRINT callback "shuffle" the blocks of the file forward with each write. This would save wear-and-tear on $buf (but not your disk!).