Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: File::Copy and wildcards

by eyepopslikeamosquito (Chancellor)
on Dec 11, 2019 at 10:46 UTC ( #11109969=note: print w/replies, xml ) Need Help??

in reply to File::Copy and wildcards

Dug out a primitive little helper function I wrote years ago in case it's of use. Just does a simple non-recursive copy of wild card files from one dir to another. Not proud of it but it still seems to work fine. Might be useful if you just need something small and simple:

use strict; use warnings; use File::Copy; use File::Basename; =head2 copy_files_wild FROMDIR TODIR VERBOSE WILD Copy files in wildcard WILD from FROMDIR to TODIR. Return the number of files successfully copied. Die if something goes wrong. =cut sub copy_files_wild { my ( $fromdir, $todir, $verbose, $wild ) = @_; print "copy '$fromdir/$wild' to '$todir'.\n"; -d $fromdir or die "error: dir '$fromdir' not found\n"; -d $todir or die "error: dir '$todir' not found\n"; $fromdir =~ s/ /\\ /g; # Escape any spaces in $fromdir my $ncopy = 0; while ( glob("$fromdir/$wild") ) { next unless -f; my $fname = File::Basename::basename($_); my $targ = "$todir/$fname"; $verbose and print "$fname\n"; if ( File::Copy::copy( $_, $targ ) ) { ++$ncopy; } else { die "error: copy '$_' to '$targ':$!"; } } print "done.\n"; return $ncopy; } # Example my $ncopied = copy_files_wild( 'DIR1', 'DIR2', 1, '*.txt' ); print "$ncopied files copied\n";

Replies are listed 'Best First'.
Re^2: File::Copy and wildcards
by haukex (Chancellor) on Dec 11, 2019 at 17:36 UTC

    Yes, glob is one possible solution, however, there are quite a few caveats to its use, especially when interpolating variables into it and using it in scalar context: To glob or not to glob

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11109969]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2020-05-26 18:20 GMT
Find Nodes?
    Voting Booth?
    If programming languages were movie genres, Perl would be:

    Results (150 votes). Check out past polls.