regex - Not moving files in perl grep in if expression -
i have current subroutine written move files in current directory /junk directory off current directory if don't have file extension. reason, none of files getting moved, , think has unless
expression. i've been working in perl week appreciated!
sub clean_old_runs { $current = cwd(); opendir(dir, $current); mkdir 'junk'; @files = readdir(dir); $num_of_files = scalar(@files); for(my $n = 0; $n < $num_of_files; $n++) { unless ( grep {/\.ext1$/} @_ or grep {/\.ext2$/} @_ or grep {/\.pl$/} @_) { move("$current/@_", "$current/junk/@_"); } } close dir; }
there's more 1 thing wrong code. here's complete working example:
#!/usr/bin/env perl use cwd; use file::copy; sub clean_old_runs { $current = cwd(); opendir(dir, $current); mkdir 'junk'; @files = readdir(dir); $num_of_files = scalar(@files); foreach $file (@files) { unless ($file =~ /\.ext[12]$/ or $file =~ /\.pl$/) { move("$current/$file", "$current/junk/$file"); } } close dir; } clean_old_runs();
i'll walk through wrong pieces of original code 1 @ time:
my @files = readdir(dir); $num_of_files = scalar(@files); for(my $n = 0; $n < $num_of_files; $n++) { # ... }
here @files
contains actual file names. for
loop doesn't iterate on files. thus, i've changed loop use foreach
iteration since have array containing files care about.
next unless
logic in fact wrong suspected:
unless ( grep {/\.ext1$/} @_ or grep {/\.ext2$/} @_ or grep {/\.pl$/} @_) { move("$current/@_", "$current/junk/@_"); }
in particular, @_
variable arguments function, doesn't appear given any, it's unclear context since don't show invocation of clean_old_runs
. regardless, appears want operate on @files
inside function. furthermore, in version, i'm iterating on @files
, doesn't make sense use grep
here, in version running grep
many times each file if ran in loop.
i combined 2 patterns simplify things /\.ext[12]$/
matches both /\.ext1/
, /\.ext2/
.
Comments
Post a Comment