Poor division of work. Input, processing and output are all intermixed.
You have two vars named @bak. One's never used, the other is declared before it should be.
You only ever put one element in the array @bak. Maybe you shouldn't be using an array.
The whole point of using File::Find was to avoid using the shell. But then you go and pass filenames to the shell without converting them to shell literals first. That's buggy. The most common failure is that it won't delete the files you intend to delete. (Consider a file with a space in its name.) It could also delete files you did not intend to delete, and it can even execute arbitrary commands. Worst case, imagine if someone created a file named "; rm -rf ~ ; .bak". You can use the multi-argument form of system to avoid the shell, or you could use unlink.
use strict; use warnings; use File::Find qw( find ); my $search_dir = '/emc/cccadm/scripts/perl/etc-test'; { print "Are you sure you would like to delete all *.bak ". "files that exist in: $search_dir [yes/no] "; chomp( my $answer = lc(<STDIN>) ); if ($answer ne 'y' && $answer ne 'yes') { die("You did not enter [yes]. Exiting program.\n"); } my @bak = find_bak_files($search_dir); if (!@bak) { # Why is this worthy of being said? warn("No files were found\n"); } for (@bak) { unlink($_) or warn("Can't delete $_: $!\n"); } } sub find_bak_files { my ($dir) = @_; my @bak; find( sub { push @bak, $File::Find::name if /\.bak\z/ && -f; }, $dir); return @bak; }
If it wasn't for the useless warning, you could shorten the above to
use strict; use warnings; use File::Find qw( find ); my $search_dir = '/emc/cccadm/scripts/perl/etc-test'; { print "Are you sure you would like to delete all *.bak ". "files that exist in: $search_dir [yes/no] "; chomp( my $answer = lc(<STDIN>) ); if ($answer ne 'y' && $answer ne 'yes') { die("You did not enter [yes]. Exiting program.\n"); } exit(1) if !delete_bak_files($search_dir); } sub delete_bak_files { my ($dir) = @_; my $success = 1; find( sub { if (/\.bak\z/ && -f) { if (!unlink($_)) { warn("Can't delete $File::Find::name: $!\n"); $success = 0; } } }, $dir); return $success; }
In reply to Re: Need help deleting *.bak files
by ikegami
in thread Need help deleting *.bak files
by MikeDexter
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |