in reply to Subroutine to delete one file and copy one file to another

I would add a safeguard:

if (not -d $delTemp) { unlink $delTemp; } else { warn "Whoaaaah. Hold it. $delTemp is a directory!\n"; }

Ideally this would never trigger, but if it does you have prevented some serious trouble:

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.
-- http://perldoc.perl.org/functions/unlink.html

Replies are listed 'Best First'.
Re^2: Subroutine to delete one file and copy one file to another
by afoken (Chancellor) on Jul 21, 2015 at 16:50 UTC
    if (not -d $delTemp) { unlink $delTemp; }

    Unfortunately, this opens the door for race conditions (see https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use). The documentation that you cited shows that it is save to use unlink even on directories. It will simply fail. You won't notice, though, because you don't check for errors here. (Just add or die "Can't unlink $delTemp: $!" after unlink $delTemp).

    There is only one way to make unlink dangerous, and all of the following must happpen:

    1. use an operating system that allows unlinking a directory
    2. be root
    3. start the script with perl -U script.pl or change the shebang line to include the -U flag

    A quick search shows that Linux does not unlink directories, but returns EISDIR instead. FreeBSD behaves the same. OpenBSD seems to allow unlinking directories, depending on the filesystem, but only for root. NetBSD seems to behave like OpenBSD.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)