Deleting a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Studentmadhura05
    New Member
    • Nov 2006
    • 25

    Deleting a file

    Hi,
    Is there a way to delete a file at the start of the code in Perl?
    I want to append to that file withing in code but next time I run it it should delete the contents of that file and start all over again.
    Thanks,
    M
  • GunnarH
    New Member
    • Nov 2006
    • 83

    #2
    Originally posted by Studentmadhura0 5
    Is there a way to delete a file at the start of the code in Perl?
    I want to append to that file withing in code but next time I run it it should delete the contents of that file and start all over again.
    If I understand you correctly, simply open()ing the file in the MODE '>' will do what you want.
    Code:
    open my $fh, '>', 'somefile'
      or die "Couldn't open somefile: $!";

    Comment

    • Studentmadhura05
      New Member
      • Nov 2006
      • 25

      #3
      If open the file with >, it does not let me append the data inside the code. I want it to append within the code but make it blank when the code starts.

      Do I make sense?

      Comment

      • GunnarH
        New Member
        • Nov 2006
        • 83

        #4
        Originally posted by Studentmadhura0 5
        If open the file with >, it does not let me append the data inside the code.
        What makes you believe that? Do you possibly have some code that demonstrates the claimed behaviour?

        Comment

        • miller
          Recognized Expert Top Contributor
          • Oct 2006
          • 1086

          #5
          You can still append data when you open a file in write/clobber mode. It only clobbers when you first open and then any subsequent write is an append. This sounds like exactly what you need.

          If your problem is that you do not want to keep the file handle open for some reason, then you can do a unlink instead at the beginning of your script and then do any subsequent opens using append '>>':

          http://perldoc.perl.or g/functions/unlink.html

          Comment

          • Studentmadhura05
            New Member
            • Nov 2006
            • 25

            #6
            Thanks guys....You were right opening the file with a '>' served my purpose. When I tried it initailly I had put the 'Close' command in a wrong place and thats why the file was not egtting appended :) ...sorry!
            Thanks..!!

            Comment

            Working...