An alternative to doing the whole thing with a regex would be to split into individual path elements then push joined elements onto the array, popping elements off the end until there's nothing left.
use 5.026;
use warnings;
use Data::Dumper;
my @paths = qw{
/abc/def/ghi
/wxy/z
/usr/local/lib/x86_64-linux-gnu/perl/5.26.1
bin/fred
somefile
};
foreach my $path ( @paths )
{
my @elems = split m{/}, $path;
my @arr;
while ( @elems )
{
last if @elems == 1 && ! $elems[ 0 ]; # Ignore empty first ele
+ment
# if path starts with a
+/
push @arr, join q{/}, @elems;
pop @elems;
}
say $path;
print Data::Dumper->Dumpxs( [ \ @arr ], [ qw{ *arr } ] );
say q{-} x 30;
}
The output.
/abc/def/ghi
@arr = (
'/abc/def/ghi',
'/abc/def',
'/abc'
);
------------------------------
/wxy/z
@arr = (
'/wxy/z',
'/wxy'
);
------------------------------
/usr/local/lib/x86_64-linux-gnu/perl/5.26.1
@arr = (
'/usr/local/lib/x86_64-linux-gnu/perl/5.26.1',
'/usr/local/lib/x86_64-linux-gnu/perl',
'/usr/local/lib/x86_64-linux-gnu',
'/usr/local/lib',
'/usr/local',
'/usr'
);
------------------------------
bin/fred
@arr = (
'bin/fred',
'bin'
);
------------------------------
somefile
@arr = (
'somefile'
);
------------------------------
A little more long-winded but possibly simpler to understand. I hope this is helpful.