0

ls /foo/bar/ lrwxr-xr-x a1 -> ../../../a1 lrwxr-xr-x a2 -> ../../../a2 lrwxr-xr-x a3 -> ../../../a3

This is a curtailed output of ls.

My goal: 1. Go to /foo/bar/ and find the latest version of a (which is a symbolic link). So in this case, a3. Copy the contents of a3 to a temp location

I am trying to use File::Find::Rule but I am unable to figure out how to use it to list all the symbolic links. Reading through various Google sites, I see people explaining how to follow the symbolic links but not to list them.

What I have figured out so far:

my $filePath = "/foo/bar"; my @files = File::Find::Rule->file->in(filePath);

This returns an empty array because there there are no files only symbolic links in /foo/bar. I also tried my @files = File::Find::Rule->in($makeFilePath)->extras({follow =>1}); but I feel that is asks to follow the symbolic link rather than list them.

4

1 回答 1

4

使用File::Find::Rule中提供的-X 测试同义词symlink中的方法

use warnings 'all';
use strict;

use File::Find::Rule;

my $rule = File::Find::Rule->new;

my @links = $rule->symlink->in('.');

print "@links\n";

这会-l在当前目录中找到所有满足文件测试的文件。另请参阅-X

有了手头的链接列表,您可以使用-M文件 test 或stat(或其File::stat按名称接口)按目标文件的时间戳对其进行排序。例如

use List::Util 'max';
my %ts_name = map { (stat)[9] => $_ } @links;
my $latest = $ts_name{ max (keys %ts_name) };

还有其他方法可以对列表进行排序/过滤/等。如果您使用-M,那么您需要min. 如果您出于某种原因想要链接本身lstat的时间戳,请改用。该模块还提供了mtime一种处理时间戳的方法,但它是用于搜索的,不适合排序。

请注意,您不必先实际创建对象,而是可以直接执行

use File::Find::Rule;
my @links = File::Find::Rule->symlink->in('.');

要复制/移动内容,请使用 core File::Copy,而对于临时文件 core File::Temp很有用。

于 2016-11-10T18:34:21.280 回答