Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2016-10-28 19:18 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (386 votes). Check out past polls.