How to copy all files of a certain type using Perl?

Now i'm using something like

copy catfile($PATH1, "instructions.txt"), catfile($ENV{'DIRWORK'}); 

separately for each of the .txt files that I want to copy. This code is portable because it does not use any OS-specific commands.

How can I copy all text files from $PATH1 to DIRWORK when I do not know the individual names of all the files, while maintaining portable code?

+4
source share
4 answers

You can use the main module File::Copy as follows:

 use File::Copy; my @files = glob("$PATH1/*.txt"); for my $file (@files) { copy($file, $ENV{DIRWORK}) or die "Copy failed: $!"; } 
+7
source

Using core File :: Find and File :: Copy and assume that you want all .txt files in $PATH1 copied to $ENV{DIRWORK} , and also assuming that you want it to recurs ...

 use strict; use warnings; use File::Find; use File::Copy; die "ENV variable DIRWORK isn't set\n" unless defined $ENV{DIRWORK} and length $ENV{DIRWORK}; die "DIRWORK $ENV{DIRWORK} is not a directory\n" unless -d $ENV{DIRWORK}; my $PATH1 = q{/path/to/wherever}; die "PATH1 is not a directory" unless -d $PATH1; find( sub{ # $_ is just the filename, "test.txt" # $File::Find::name is the full "/path/to/the/file/test.txt". return if $_ !~ /\.txt$/i; my $dest = "$ENV{DIRWORK}/$_"; copy( $File::Find::name, $dest ) or do { warn "Could not copy $File::Find::name, skipping\n"; return; } }, $PATH1 ); 

Release him;)

Alternatively, why don't you use bash ?

 $ ( find $PATH1 -type f -name '*.txt' | xargs -I{} cp {} $DIRWORK ); 
+2
source

If you are guaranteed to work in a Unix system (for example, do not care about portability), I will go against my own inclinations and consider best practices and recommend considering the use of "cp" :)

 system("cp $PATH1/*.txt $ENV{'DIRWORK'}"); # Add error checking and STDERR redirection! 

For Perl's own solution, combine the globbed file list (or File :: Find) with File :: Spec the ability to find the actual file name

 my @files = glob("$PATH1/*.txt"); foreach my $file (@files) { my ($volume,$directories,$filename) = File::Spec->splitpath( $file ); copy($file, File::Spec->catfile( $ENV{'DIRWORK'}, $filename ) || die "$!"; } 
0
source

File :: Find and file :: Copy transferred:

 use File::Find; use File::Copy; find( sub { return unless ( -f $_ ); $_ =~ /\.txt$/ && copy( $File::Find::name, $ENV{'DIRWORK'} ); }, $PATH1 ); 
0
source

All Articles