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

this code fails to delete any globbed filename after the first:
$prefix=test; $runid=12; unlink glob("$prefix$runid.*") || print"Error removing files $!\n";
Remove the || print... and it deletes all files globbed.
Anyone know why?

Replies are listed 'Best First'.
Re: unlink glob
by ikegami (Patriarch) on Feb 28, 2008 at 00:22 UTC

    The fix suggested (unlink glob("$prefix$runid.*") or ...) will only report an error if no files can be unlinked. If only some files cannot be unlinked, no error will be reported. You probably want

    unlink $_ or print "Error removing file \"$_\": $!\n" for glob("$prefix$runid.*");

    I also doubt $! is set properly, especially when processing multiple files.

Re: unlink glob
by tirwhan (Abbot) on Feb 27, 2008 at 22:24 UTC

    Replace the || with "or" and read up about operator precedence in perlop.

    Update: ikegami is absolutely right, please follow his advice.

    All dogma is stupid.
Re: unlink glob
by kyle (Abbot) on Feb 27, 2008 at 22:36 UTC

    The precedence for || is pretty high. Your unlink would give a list context for glob(), but || gives it a scalar context instead. What you wrote is parsed as:

    unlink ( glob(...) || print "..." );

    This might show what's going on a little more:

    sub print_context { my $wa = wantarray; print $wa ? 'list' : defined $wa ? 'scalar' : 'void'; print "\n"; return $wa ? (1, 2) : 'x'; } print "with || :\n"; print print_context() || print "error"; print "\n"; print "with or :\n"; print print_context() or print "error"; print "\n"; __END__ with || : scalar x with or : list 12

    Anyway, the short answer is to use or instead of ||, or use parentheses around the argument to unlink. These should work:

    unlink( glob(...) ) || print "..."; unlink glob(...) or print "...";
Re: unlink glob
by Anonymous Monk on Feb 28, 2008 at 12:28 UTC
    perl -MO=Deparse,-p temp.pl ($prefix = 'test'); ($runid = 12); use File::Glob (); unlink((glob("$prefix$runid.*") || print("Error removing files $!\n")) +); temp.pl syntax OK