package WildcardArgs; # this module processes files in directories # example usage: # handlearg($_, sub { printf("file: %s\n", @_); } ) for @ARGV; # optional properties: # recurse=>1 : to recurse into subdirectories, otherwise only the directo # dirfilter=>sub {} : only process directories matching the filter. # glob=>1 : process wildcards ( this is automatic on win32 platforms ) # note: under cygwin '-r $file' returns false when the perms are -rwxrwx---, even though the current user is in the correct group. use strict; use base 'Exporter'; use Config; our @EXPORT=qw(handlearg); sub canread { return -r $_[0] || ($Config{osname} eq 'cygwin' && -f $_[0]); } sub makeFullPath { my ($full, @parts)= @_; $full ||=""; for my $path (@parts) { next if (!defined $path); $path =~ s{^/}{}; # remove leading slash $full =~ s{/?$}{/$path}; # remove trailing slash, append path } return $full; } sub processdir { my ($path, $fileproc, %opts)= @_; opendir(DIR, $path) or die "$!: reading $path\n"; my @files= readdir DIR; closedir DIR; for (@files) { next if ($_ eq "." || $_ eq ".."); my $file= makeFullPath($path, $_); if (-d $file) { next if $opts{dirfilter} && !$opts{dirfilter}->($file); $opts{recurse} && processdir($file, $fileproc, %opts); } elsif (canread($file)) { $fileproc->($file); } else { warn "ignoring $file\n"; } } } sub handlearg { my ($arg, $fileproc, %opts)= @_; if ($arg eq "-") { $fileproc->(); } elsif (-d $arg) { processdir($arg, $fileproc, %opts); } elsif (canread($arg)) { $fileproc->($arg); } elsif ($opts{'glob'} || $Config{'osname'} eq 'MSWin32') { for my $f (glob($arg)) { if (-d $f) { processdir($f, $fileproc, %opts); } elsif (canread($f)) { $fileproc->($f); } } } } 1;