Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Breaking file path into segments

by johngg (Canon)
on Apr 13, 2019 at 11:01 UTC ( #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
Node Status?
node history
Node Type: note [id://1232536]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2020-05-25 09:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (145 votes). Check out past polls.

    Notices?