Is there a cleaner way for File::Find to return a list of wanted files?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 03:28:45

问题


I find the design choice behind File::Find::find a little surprising. The examples I've come across all show find used in void context.

The documentation also clarifies that the \&wanted coderef in find( \&wanted, @dirs ) is not meant to be a filter (emphasis my own):

The wanted() function does whatever verifications you want on each file and directory. Note that despite its name, the wanted() function is a generic callback function, and does not tell File::Find if a file is "wanted" or not. In fact, its return value is ignored.


But what if I do want to use it as a filter in a manner similar to grep? I'm curious to know if there's another way to write the following:

use strict;
use warnings;
use feature 'say';

use File::Find;

my $wanted = qr/^\d{2}_/;  # e.g.

my @wanted;
find( sub { -f && /$wanted/ && push @wanted, $_ }, '.' );

# I wish my @wanted = find( ... ); worked

say for @wanted;

回答1:


Looking on CPAN, I find several alternative interfaces to File::Find available that aim to simplify the interface.

I would try File::Finder, by well-known Perl expert Randal Schwartz, first.

File::Find::Rule is another one.

(It is probably safe to say that, if people are writing modules to do this, there is no easy built-in way to do it.)




回答2:


I think you're using it in the right way. The only things you can do is to wrap the find function inside another one that creates the array (with push) and then return it.

sub find_to_array {
    my $wanted = shift;
    my @array;
    find( sub { -f && /$wanted/ && push @array, $_ }, '.' );
    return @array;
}

In this way you can have what you were looking for, but it's almost the same as you have done.



来源:https://stackoverflow.com/questions/12620423/is-there-a-cleaner-way-for-filefind-to-return-a-list-of-wanted-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!