One way that I can see how to do this is with the following subroutine called prepend_file():

#!/usr/bin/perl -w use strict; use IO::File; use constant FILE => 'test.txt'; use constant DATA => "this should be the first line\n"; use constant BUFFER_SIZE => '8096'; my $fh = prepend_file(FILE, DATA, BUFFER_SIZE); while(my $line = <$fh>) { print $line; } sub prepend_file { my $file = shift; my $data = shift; my $buffer_size = shift; #Open a temporary and source file handle my $temp_fh = IO::File->new_tmpfile or die "Could not open a temporary file: $!"; my $fh= IO::File->new($file, O_RDWR) or die "Could not open file ", FILE, ": $!"; #Write the first bit of data $temp_fh->syswrite($data); #Copy all the $data from the $fh to the temp file handle $temp_fh->syswrite($data) while $fh->sysread($data, $buffer_size); $temp_fh->sysseek(0, 0); $fh->sysseek(0, 0); #Write out the new file from the temporary file handle $fh->syswrite($data) while $temp_fh->sysread($data, $buffer_size); #could return anything here, I just chose the file handle just #in case we needed to use it for something. return $fh->sysseek(0, 0) && $fh; } __END__

It uses IO::File's new_tmpfile() method to create a temporary file. You then only have to deal with the single filehandle, and IO::File takes care of throwing away the temp file when you're done. I wanted to make sure it could handle most sizes of files, even those that exceed available memory, this is why I used a temporary file and not just memory/slurping.


In reply to Re: Re: Prepending to a file by dkubb
in thread Prepending to a file by electronicMacks

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.