#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use Path::Tiny; my $path = '/abc/def/ghi'; my $climb = path($path); my @paths = $climb; push @paths, $climb until ($climb = $climb->parent) eq '/'; say for @paths;
File::Spec is a core module that can handle the path as well:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use File::Spec; my $path = '/abc/def/ghi'; my @paths = 'File::Spec'->splitdir($path); for my $i (reverse 0 .. $#paths) { $paths[$i] = join '/', @paths[0 .. $i]; } shift @paths; # Remove the empty path. say for @paths;
But a regex with split will work similarly:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use Path::Tiny; my $path = '/abc/def/ghi'; my @paths = split m{(?<=.)/}, $path; for my $i (reverse 0 .. $#paths) { $paths[$i] = join '/', @paths[0 .. $i]; } say for @paths;
I used a lookbehind assertion to skip the empty path before the first slash.
In reply to Re: Breaking file path into segments
by choroba
in thread Breaking file path into segments
by cherio
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |