in reply to Breaking file path into segments
I agree with others that a path-processing module is the way to go here, but if you just gotta have a regex, here's another:
With Perl version 5.10+, the odd-looking (?!) can become (*FAIL) from Special Backtracking Control Verbs in perlre (but the compiler will optimize it to (*FAIL) anyway). With version 5.18+ (IIRC), the package-global array @dirs can become a my array; that bug was fixed.c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "print qq{perl version: $]}; ;; my $path = '/abc/def/ghi'; ;; local our @dirs; $path =~ m{ (\A (?: / [^/]+ \b)+) (?{ push @dirs, $^N }) (?!) }xms; ;; dd \@dirs; " perl version: 5.008009 ["/abc/def/ghi", "/abc/def", "/abc"]
Update 1: On second thought, the \b anchor is a bit too alnum-specific: make it (?! [^/]) instead:
$path =~ m{ (\A (?: / [^/]+ (?! [^/]))+) (?{ push @dirs, $^N }) (?!) }xms;
Update 2: And if you want to reverse the order of the pieces, use a lazy quantifier:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "print qq{perl version: $]}; ;; my $path = '/=abc/def/ghi=/---'; ;; local our @dirs; $path =~ m{ (\A (?: / [^/]+ (?! [^/]))+?) (?{ push @dirs, $^N }) (?!) + }xms; ;; dd \@dirs; " perl version: 5.008009 ["/=abc", "/=abc/def", "/=abc/def/ghi=", "/=abc/def/ghi=/---"]
Give a man a fish: <%-{-{-{-<
|
|---|