Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Quick Question - Append File at Beginning?

by Kenosis (Priest)
on Nov 16, 2013 at 01:44 UTC ( #1062834=note: print w/replies, xml ) Need Help??

in reply to Quick Question - Append File at Beginning?

Is there anyway to add the new stuff to the top of the file instead of the bottom?

Perhaps the following will be helpful:

use strict; use warnings; addStuffToTopOfFile( "New Stuff!\n", 'File.txt' ); sub addStuffToTopOfFile { my ( $stuff, $file ) = @_; local @ARGV; local $^I = '.bak'; push @ARGV, $file; while (<>) { print $stuff if $. == 1; print; } unlink "$file.bak"; }

File contents before running script:

Line 1 Line 2 Line 3 Line 4

File contents after running script:

New Stuff! Line 1 Line 2 Line 3 Line 4

This solution was implicit in Anonymous Monk's reply, but you send a string and file you want prepended to the subroutine. The script makes, and then deletes, a backup file during the process.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062834]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2018-02-19 00:05 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (257 votes). Check out past polls.