http://qs321.pair.com?node_id=467211

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

Hi, I need to delete a file before executing a script. The file itself is recreated by the script using the filehandle >>. However, when i try to unlink the file, the error "No such file or directory" is printed. The file does though exist?
unlink "data/remove.txt" or die "unable to delete $!";

Replies are listed 'Best First'.
Re: delete a file
by reasonablekeith (Deacon) on Jun 16, 2005 at 09:15 UTC
    it works fine here. Check your permissions and/or working directory?
    #!/usr/bin/perl use Cwd; print getcwd();
    ---
    my name's not Keith, and I'm not reasonable.
Re: delete a file
by jpeg (Chaplain) on Jun 16, 2005 at 09:15 UTC
    Maybe your script isn't creating that file where you think it is, or your script isn't in chdir'd to the right directory. Try printing getcwd before creating and deleting and abs_path to the file. both functions are in Cwd.pm.

    --
    jpg
      cwd prints the location that the script is running from, therefore, the link to delete the file is correct?
        cwd should match the directory containing the file, for your purposes.

        Why don't you post the entire script?

        --
        jpg
Re: delete a file
by TedPride (Priest) on Jun 16, 2005 at 12:33 UTC
    Pardon me for asking stupid questions, but why aren't you just using > instead of deleting the file and using >>?
Re: delete a file
by kyoshu (Curate) on Jun 16, 2005 at 09:15 UTC
    you do not have the file on the system or you
    are trying to delete file which you can not delete
    because of file permisions, or you execute your
    script from some other directory than ../data/.
    # mkdir dir
    # touch dir/file
    # ls dir/
    file
    # perl -e 'unlink "dir/file" or die "failure\n";'
    # ls dir/
    #
    
Re: delete a file
by Anonymous Monk on Jun 16, 2005 at 10:08 UTC
    What happens if you write that as:
    if (-e "data/remove.txt") { unlink "data/remove.txt" or die "unable to delete $!"; }

    Are you sure you are using the filehandle >>? That's a pretty weird name for a filehandle. Or do you mean that you are using the append mode when opening a file? If so, why use append if the file isn't supposed to be there in the first place? It's not wrong (although I'm not sure if opening of a non-existing file using append mode actually works on all platforms), but people usually open a non-existing file in write only mode.

    A reply falls below the community's threshold of quality. You may see it by logging in.