I'd recommend Tie::File as well (compare the following code to the example shown by broquaint above). Nevertheless, here is a simple example using traditional methods:
#!/usr/bin/perl -w use strict; # Open the file in read mode open FILE, "file.txt" or die "Error message here $!"; # Slurp in the file my $str = do{local $/; <FILE>}; close FILE or die "Error message here $!"; # Reopen the file in write mode (clobbers old file) open FILE, ">file.txt" or die "Error message here $!"; # Add some text print FILE "Prepend this text.\n"; # Add the old contents of the file. print FILE $str; close FILE or die "Error message here $!";
This is similar except that the file is only opened once (in read/write mode):
#!/usr/bin/perl -w use strict; # Open the file for reading and writing open FILE, "+<file.txt" or die "Error message here $!"; # Slurp in the file my $str = do{local $/; <FILE>}; # Rewind the file seek FILE, 0, 0; # Add some text print FILE "Prepend this text.\n"; # Add the old contents of the file. print FILE $str; close FILE or die "Error message here $!";

Both of these examples assume that the data in the file isn't too large to be slurped into memory. If it is then you can modify the code to use an intermediary file.

--
John.


In reply to Re: insert into beginning of file by jmcnamara
in thread insert into beginning of file by rchou2

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.