in reply to Breaking file path into segments

I prefer Path::Tiny to handle paths for me:
#!/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.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Breaking file path into segments
by shawnhcorey (Friar) on Apr 15, 2019 at 14:31 UTC

    File::Spec is a standard module and comes with Perl. For a list of standard modules, see perldoc perlmodlib

    If your code is going to be run on a different machine than your development one, using standard modules means you don't have to distribute and maintain additional code (the modules).

      > you don't have to distribute and maintain additional code

      Unless you work on a RedHat based Linux distribution where you need to install the perl-PathTools package. Installing perl-Path-Tiny is comparably complex.

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]