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";