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

Hello Monks, The below program is having an issue with the unlink statement. All other components do what they are supposed to but its giving a 'Use of uninitialized value $_ in unlink (filename)' error for every file I am trying to delete. Purpose of script: collect all the data from .matched files and compile them into one and delete all the .matched files. Would appreciate any help with this. Thanks!
use strict; use warnings; my $directory = 'C:\test'; chdir($directory) or die "Can't chdir to $directory $!"; opendir(DIR, $directory) || die "Couldn't opendir: $!\n"; my @files = grep(/\.matched$/, readdir(DIR)); my $destdir = 'C:\test'; if (@files) { foreach(@files){ print $_, "\n";} open COMBINED, '+>>', "$destdir/combined.matched" or die "Can't op +en file, combined.matched: $!"; foreach(@files){ open MATCHED, '<', "$_" or die "Can't open file, $_: $!"; while(<MATCHED>){ print COMBINED "$_";} close MATCHED; } close COMBINED; } unlink(@files); close $directory; exit 0;

Replies are listed 'Best First'.
Re: Need help with unlink error
by zentara (Cardinal) on Aug 11, 2011 at 16:26 UTC
    unlink probably wants full paths to the files. Try this, and see what errors come up
    foreach my $file ( @files ) { unlink $file or warn "Could not unlink $file: $!"; }

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: Need help with unlink error
by toolic (Bishop) on Aug 11, 2011 at 16:50 UTC
    Try to move your unlink inside your if (@files) { block. It seems like, from a logical standpoint, that's where you would want it. Why would you want to call unlink on an empty list?
Re: Need help with unlink error
by jethro (Monsignor) on Aug 11, 2011 at 16:29 UTC
    unlink( map($directory.'\\'.$_, @files) );
Re: Need help with unlink error
by cdarke (Prior) on Aug 12, 2011 at 08:45 UTC
    Not you question I know, but:
    close $directory;
    will fail as well. $directory is the name of the directory, not the directory handle. You probably want:
    closedir(DIR);
    and you could move that earlier in the code, after your readdir.
Re: Need help with unlink error
by Anonymous Monk on Aug 11, 2011 at 17:08 UTC
    Do you wonder sometimes, why C:\test\combined.matched is no longer there?