http://www.perlmonks.org?node_id=1201695

Earlier today a new monk (mz2255) attempted to post a question on SoPW about recursively searching for files in a directory tree. He was having issues with excluding . and .. and also with rel2abs and nested readdir calls and what have you. He was unable to get the SoPW to post and ended up posting on his scratch pad, so here is a reply for mz2255, and a demonstration of what I would call the modern way to do the job, using Path::Tiny.

Note that the regexp is minimally modified from the OP and likely needs improvement before it can be used reliably for the OP's desired outcome. Left here for demo purposes.

use strict; use warnings; use feature qw/ say /; use Data::Dumper; $Data::Dumper::Sortkeys = 1; use Path::Tiny; my $root_dir = Path::Tiny->tempdir; _populate_for_demo( $root_dir ); my $re = qr/ (?:\w|\d)+ _ \w+ _ .+ _R(1|2)_ .+ /x; my %results; $root_dir->visit( sub { $_->is_file and push @{ $results{$1} }, "$_" if /$re/ }, { recurse => 1 }, ); say Dumper \%results; exit; sub _populate_for_demo { my $temp_dir = shift; path("$temp_dir/$_/aa_bb_cc_R1_dd.tmp")->touchpath for 'foo','bar' +; path("$temp_dir/$_/aa_bb_cc_R2_dd.tmp")->touchpath for 'baz','qux' +; return $temp_dir; } __END__
Output:
$ perl 1201682.pl $VAR1 = { '1' => [ '/tmp/0JbuMoAJix/bar/aa_bb_cc_R1_dd.tmp', '/tmp/0JbuMoAJix/foo/aa_bb_cc_R1_dd.tmp' ], '2' => [ '/tmp/0JbuMoAJix/baz/aa_bb_cc_R2_dd.tmp', '/tmp/0JbuMoAJix/qux/aa_bb_cc_R2_dd.tmp' ] };

Update: moved creation of the temp dir to main for clarity


The way forward always starts with a minimal test.