write to file in append mode
devlele
created: 2006-01-04 13:50:25


Hi Monks,

I am using following code to write to a text file. open(FH, "> sample.txt") or die("Cannot write to file: $!\n"); I want to open that file for writing in "append" mode.

Can anyone help me how to modify it so that I can use it to append the text ?

Thanks.
Re: write to file in append mode
created: 2006-01-04 13:53:22
Replace > with >> to get append mode.

Phil

Re: write to file in append mode
created: 2006-01-04 13:57:52

Take a look at perldoc -f open for a complete answer to this question. This will do what you want:

open(my $handle,">>","sample.txt") or die("Cannot write to file: $!\n");

Note that this uses the three-argument version of open and uses a lexical variable as a filehandle, both are recommended best practices and you should stick to them (see the perldoc for why).


A computer is a state machine. Threads are for people who can't program state machines. -- Alan Cox
Re: write to file in append mode
created: 2006-01-04 15:42:20
      I want to open that file for writing in "append" mode.

And just to be different, try this:

#!/usr/bin/perl -wT
use strict;
use Tie::File;

my @ry;

tie @ry,"Tie::File","myfile.txt" or die $!;

push @ry,"stuff";

untie @ry;

exit(0);

In Perl there is always more than one solution to a problem.... and nobody expects the Perl Inquisition!

update: fixed minor typo pointed out by [Happy-the-monk]


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: write to file in append mode
created: 2006-01-05 04:52:22
Hey devlele,

     You have to use operator ">>" while opening. If you want to open in R+W mode you just put the "+" operator infront as "+>> $fileName". You better go through the help pages of "open" function.

You also take a look at the "seek" function, that will help you to handle the file pointers effectively.



Regards,
S.Venni Rajan.
"A Flair For Excellence."
                -- BK Systems.

perlmonks.org content © perlmonks.org and blue_cowdawg, devlele, philcrow, tirwhan, vennirajan

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03