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

Hello,
I am using unlink to delete empty files, but it is not working in my script.
I would appreciate if someone could point me in the right direction.
my $maid_dir = "C:/Documents and Settings/mydir/Desktop/current/rm_fil +es"; opendir my $dh, "$maid_dir"; # directory to search my @files = readdir $dh; foreach my $f (@files){ my $size = -s $f; print $size, "\n"; print Dumper($f); if($size < 1 ){ unlink("$size"); } }
Any help will be appreciated.

Replies are listed 'Best First'.
Re: using unlink to delete files
by davorg (Chancellor) on Jun 22, 2009 at 22:06 UTC

    If unlink fails then $! will be set. You could try printing the value in there.

    You are in the wrong directory. You need to either chdir $maid_dir or prepend $maid_dir to the files that you are trying to delete.

    You appear to be trying to delete $size rather than $f.

    There is no need to quote the variable in your call to unlink.

    --

    See the Copyright notice on my home node.

    Perl training courses

Re: using unlink to delete files
by Your Mother (Archbishop) on Jun 22, 2009 at 23:18 UTC

    AnonMonk above was pointing you in the right way. You seem to be trying to remove the stat'ed sizes, not the actual files. Plus readdir doesn't keep the file paths so even if you were doing unlink($f), it would fail unless you were in the right place. Look around in here for sample code for readdir if you get stuck.

Re: using unlink to delete files
by Anonymous Monk on Jun 22, 2009 at 22:43 UTC
    use autodie
    perl -Mautodie -e "unlink(2)" Can't unlink('2'): No such file or directory at -e line 1
Re: using unlink to delete files
by moritz (Cardinal) on Jun 22, 2009 at 21:21 UTC

    Update: I misread the question, sorry for the noise; please ignore

    Read the documentation, it actually helps:
    Note: "unlink" will not attempt to delete directories unless you are superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using "unlink" on directories is not supported on many operating systems. Use "rmdir" instead.

    Do you have any suggestions on how that could have been formulated more clearly, or at a more appropriate place in the documentation?

Re: using unlink to delete files
by scorpio17 (Canon) on Jun 23, 2009 at 13:51 UTC

    I think you what to do this:

    for my $f (@files) { if (-z "$maid_dir/$f") { unlink("$maid_dir/$f"); } }

    Note that the -z file test returns true for zero-size files, and readdir gives you filename, but not the full path.