Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Breaking file path into segments

by johngg (Canon)
on Apr 13, 2019 at 11:01 UTC ( [id://1232536]=note: print w/replies, xml ) Need Help??


in reply to Breaking file path into segments

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.

Cheers,

JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1232536]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-26 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found