in reply to Breaking file path into segments
#!/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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Breaking file path into segments
by shawnhcorey (Friar) on Apr 15, 2019 at 14:31 UTC | |
by choroba (Cardinal) on Apr 15, 2019 at 14:48 UTC |