devlele has asked for the wisdom of the Perl Monks concerning the following question:



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.

Replies are listed 'Best First'.
Re: write to file in append mode
by tirwhan (Abbot) on Jan 04, 2006 at 18:57 UTC

    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
by philcrow (Priest) on Jan 04, 2006 at 18:53 UTC
    Replace > with >> to get append mode.

    Phil

Re: write to file in append mode
by blue_cowdawg (Monsignor) on Jan 04, 2006 at 20:42 UTC
        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
by vennirajan (Friar) on Jan 05, 2006 at 09:52 UTC
    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.