Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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.


Comment on Re: Quick Question - Append File at Beginning?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062834]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2015-07-04 11:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (59 votes), past polls