5

我在下面的代码中使用File::Find/home/user/data路径中查找文件。

use File::Find;

my $path = "/home/user/data";
chdir($path);
my @files;

find(\&d, "$path");

foreach my $file (@files) {
print "$file\n";
}

sub d {
-f and -r and push  @files, $File::Find::name;
}

当我将 dir 路径更改为我需要搜索文件的路径时,它仍然为我提供了具有完整路径的文件。IE

/home/user/data/dir1/file1
/home/user/data/dir2/file2
and so on...

但我想要像这样的输出

dir1/file1
dir2/file2
and so on...

谁能建议我仅从当前工作目录中查找文件和显示的代码?

4

2 回答 2

13

以下将打印 下所有文件的路径$base,相对于$base(不是当前目录):

#!/usr/bin/perl
use warnings;
use strict;

use File::Spec;
use File::Find;

# can be absolute or relative (to the current directory)
my $base = '/base/directory';
my @absolute;

find({
    wanted   => sub { push @absolute, $_ if -f and -r },
    no_chdir => 1,
}, $base);

my @relative = map { File::Spec->abs2rel($_, $base) } @absolute;
print $_, "\n" for @relative;
于 2009-11-10T13:06:56.040 回答
3

删除它怎么样:

foreach my $file (@files) {
$file =~ s:^\Q$path/::;
print "$file\n";
}

注意:这实际上会改变@files.

根据评论,这不起作用,所以让我们测试一个完整的程序:

#!/usr/local/bin/perl
use warnings;
use strict;
use File::Find;

my $path = "/usr/share/skel";
chdir($path);
my @files;

find(\&d, "$path");

foreach my $file (@files) {
$file =~ s:^\Q$path/::;
print "$file\n";
}

sub d {
-f and -r and push  @files, $File::Find::name;
}

我得到的输出是

$ ./find.pl
点.cshrc
点登录
dot.login_conf
点.mailrc
点配置文件
点.shrc

这对我来说似乎工作正常。我也用带有子目录的目录测试过,没有问题。

于 2009-11-10T13:05:43.700 回答