代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

如何使用Perl复制特定类型的所有文件?

  •  4
  • Aakash Goel  · 技术社区  · 14 年前

    现在,我用的是

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

    为每个 .txt

    我怎么能抄 全部的 $PATH1 DIRWORK ,当我不知道所有文件的单独名称时,同时保持代码的可移植性?

    4 回复  |  直到 14 年前
        1
  •  7
  •   Eugene Yarmash    9 年前

    你可以用核心 File::Copy 这样的模块:

    use File::Copy;
    my @files = glob("$PATH1/*.txt");
    
    for my $file (@files) {
        copy($file, $ENV{DIRWORK}) or die "Copy failed: $!";
    }
    
        2
  •  2
  •   mfontani    14 年前

    使用核心 File::Find File::Copy 假设你想要所有 .txt 文件 $PATH1 $ENV{DIRWORK} ,和 假设你想让它递归。。。

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

    试一试;)

    或者,你为什么不使用 bash

    $ ( find $PATH1 -type f -name '*.txt' | xargs -I{} cp {} $DIRWORK );
    
        3
  •  0
  •   DVK    14 年前

    如果保证您在Unix系统上工作(例如,不关心可移植性),我将违背自己的习惯和公认的最佳实践,并建议您考虑使用“cp”:

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

    对于Perl本机解决方案,将globbed file list(或file::Find)与 File::Spec 能够找到实际的文件名

    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 "$!";
    }
    
        4
  •  0
  •   mlbright    10 年前

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