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

hi monks, I know its a silly question but i am just a beginner in perl what i am doing is that i am appending a string to a particular file but instead of that the whole data in that file is getting destroyed and just my string is there .I am writting the code for your convinience.the file is a regular file.
#!usr/bin/perl my $string = "export AP_IU_NUM = 41"; open(FD, ">>/users/smisra/test4.pl"); print FD ($string); close(FD)

Replies are listed 'Best First'.
Re: appending is not done
by Samy_rio (Vicar) on Aug 25, 2005 at 10:00 UTC

    Hi, Here your code is working fine. For this problem, my suggestion as follows:

    1. Append mode (>>) work is to check whether the mentioned file is present or not. if not present then it will create a new file in the given filename, otherwise it will append the string. So, you will check whether file is present or not in that particular path.

    2. Give 'die' function (to know the open statement status) as follows:

    open(FD, ">>/users/smisra/test4.pl")||die("Cannot open the file\n");

    I think it helps you.

    Regards,
    Velusamy R.

      I'd stick a $! on the end of that print. That way you can see what the error is :-)
      open(FD, ">>file_name") or die("Can't open file for appending: $!\n");
      ---
      my name's not Keith, and I'm not reasonable.
Re: appending is not done
by tlm (Prior) on Aug 25, 2005 at 10:02 UTC

    What you have written should work. What's your shell? zsh can give confusing results; in the unlikely event that this is what you're using, try adding a "\n" at the end of the string you're appending.

    BTW, you should check the return value of your open. (And to be excruciatingly correct, you should check the return value of your close too.) Also the parentheses in your print statement are not doing anything for you.

    open FD, '>>/users/smisra/test4.pl' or die "open failed: $!\n"; print FD $string; close FD or die "close failed: $!\n";

    the lowliest monk

Re: appending is not done
by samizdat (Vicar) on Aug 25, 2005 at 12:23 UTC
    The only thing I can see is that your #! line is bollixed:
        
    #!usr/bin/perl

    should be
        
    #!/usr/bin/perl

    Is it (remotely) possible that there is something going wrong with the shell call to Perl because of this? It sounds strange, but wierder things have happend, especially on systems that have been around and been upgraded since the days of punch cards. You didn't specify the OS or vintage, so I thought I'd bring this possibility up because your code should otherwise work.

    In any event, welcome to the programming world! :D