Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Add a Line to a Text File

by Athanasius (Archbishop)
on Aug 24, 2013 at 04:04 UTC ( [id://1050756]=note: print w/replies, xml ) Need Help??


in reply to Re: Add a Line to a Text File
in thread Add a Line to a Text File

Hello xanadol, and welcome to the Monastery!

Glad to see you found the solution. For the record, this is an FAQ: How do I change, delete, or insert a line in a file, or append to the beginning of a file?.

Some observations on your code:

  • Great to see you useing strict and warnings!

  • The while loop can be written more idiomatically:

  • print $fh $_ while <$fd>;
  • chomping $previous after the while loop does nothing.

If you want to prepend a line of text to an existing file in-place, you can use the core module Tie::File:

use strict; use warnings; use Tie::File; my $file = $ARGV[0] or die "$0 Usage:\n\t$0 <file>\n\n" +; tie my @array, 'Tie::File', $file or die "Cannot tie file '$file': $! +"; unshift @array, 'data'; untie @array;

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (6)
As of 2024-04-16 06:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found