Recursive Find File In Directory

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#!/usr/bin/perl -w

use utf8;
use strict;
use warnings;

sub lsrp {
    my ($dir, $sub, $ext, $print) = @_;

    my @dirs = ($dir);

    my @rets = ();

    while (my $dir = pop(@dirs)) {
        local *DH;
        if (!opendir(DH, $dir)) {
            warn "Cannot opendir $dir: $! $^E";
            next;
        }

        foreach (readdir(DH)) {
            if ($_ eq '.' || $_ eq '..') {
                next;
            }
            my $file = $dir.$_;         
            if (!-l $file && -d _) {
                $file .= '/';
                push(@dirs, $file) if $sub;
            } elsif ($file =~ /\.\Q$ext\E$/) {
                push @rets, $file;
                $print->($file) if defined($print);
            }
        }
        closedir(DH);
    }

    return @rets;
}

my $find_dir = shift @ARGV;
my $find_ext = shift @ARGV;
my $find_sub = shift @ARGV;

if (!defined($find_dir)) {
	help();
	exit;
}

if (!defined($find_ext)) {
	help();
	exit;
}

if (!defined($find_sub)) {
	$find_sub = 0;
}

if ($find_dir =~ /[^\/]$/) {
	$find_dir .= '/';
}
$find_ext =~ s/^\.//;

sub p {
	print (shift . "\n");  
}

my @files = lsrp($find_dir, $find_sub, $find_ext, \&p);

if ($#files <= 0) {
	print "Found nothing.\n";
	exit;
}

#print "Found " . $#files . ($#files <= 1 ? " file" : " files") . "\n";
#
#foreach (@files) {
#	print " -> ".$_."\n";
#}

exit;

sub help {
	print "Usage:\n";
	print "\t$0".' [directroy] [extension] [recursion]'."\n";
	print "Sample:\n\t$0 . pl 1 \n";
}