in reply to Re^2: Recursively walk up a directory tree
in thread Recursively walk up a directory tree
The cwd() function gives the full path of the... well, CWD. The match looks for a file at the end (rightmost part) of the path. If the file is not found, the regex engine effectively backtracks up a level in the directory.
The ! -f "$1/.marker" code in the (??{ CODE }) construct evaluates to '' (empty string) if the file exists at a given level, and this is interpolated into the regex pattern and always matches, hence the file is "found" at that level.
If the file is not found, the negated file test evaluates to '1' and this will probably not be found at the beginning of a directory name. However, this can fail (debug print added to show progress):
Output (with no .marker file present anywhere):use strict; use warnings; use Cwd; my $marker = '.marker'; cwd =~ m#^(.*)(?:/|$)(??{ print "at level '$1' \n"; ! -f "$1/$marker" +})# or die "'$marker' not found"; print "found '$marker' in '$1' \n";
If you have Perl version 5.10+, there's a variation that avoids this problem:c:\@Work\Perl\monks\1nickt\two\one\zero>perl find_marker_1.pl at level 'c:/@Work/Perl/monks/1nickt/two/one/zero' at level 'c:/@Work/Perl/monks/1nickt/two/one' at level 'c:/@Work/Perl/monks/1nickt/two' at level 'c:/@Work/Perl/monks/1nickt' at level 'c:/@Work/Perl/monks' found '.marker' in 'c:/@Work/Perl/monks'
Output (still no .marker file):use 5.010; # needs (?(?{ CODE })yes-pattern) regex extension use strict; use warnings; use Cwd; my $marker = '.marker'; cwd =~ m{ \A (.*) (?: / | \z) # (??{ print "at level '$1' \n"; ! -f "$1/$marker"}) (?(?{ print "at level '$1' \n"; ! -f "$1/$marker" }) (*FAIL)) }xms or die "'$marker' not found"; print "found '$marker' in '$1' \n";
Both versions of code behave the same if a .marker is present at some level, although the first version will fail if the .marker file is present above the level of, say, the 1nickt directory.c:\@Work\Perl\monks\1nickt\two\one\zero>perl find_marker_2.pl at level 'c:/@Work/Perl/monks/1nickt/two/one/zero' at level 'c:/@Work/Perl/monks/1nickt/two/one' at level 'c:/@Work/Perl/monks/1nickt/two' at level 'c:/@Work/Perl/monks/1nickt' at level 'c:/@Work/Perl/monks' at level 'c:/@Work/Perl' at level 'c:/@Work' at level 'c:' '.marker' not found at find_marker_2.pl line 62.
Give a man a fish: <%-{-{-{-<
|
|---|