Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How to Get the Last Subdirectories

by rubasov (Friar)
on Mar 11, 2010 at 22:06 UTC ( #828145=note: print w/ replies, xml ) Need Help??


in reply to How to Get the Last Subdirectories

This code is probably a little too tricky, however if I'm right, it just does what it needs to.

#! /usr/bin/perl use 5.010; use strict; use warnings; use File::Find; my $dir = $ARGV[0] // q{.}; sub deepest { return if not -d; state $prev_dir = ''; say if index $prev_dir, $_; $prev_dir = $_; } find( { wanted => \&deepest, no_chdir => 1, bydepth => 1, }, $dir );
The main idea behind this code is the following: if you traverse your directory structure in depth-first order, then you only need to check whether your current directory path is not a prefix (a slice starting at position 0) of the previous directory path. If it's not a prefix of the previous value, then print it.

To ease the understanding: your sample dir structure in depth-first order:

a/b/d/g/h a/b/d/g/i a/b/d/g # this is a prefix of the previous, so we don't want it a/b/d a/b/k # this is not a prefix of the previous, so we want it a/b/c/e a/b/c a/b a


Comment on Re: How to Get the Last Subdirectories
Select or Download Code
Re^2: How to Get the Last Subdirectories
by almut (Canon) on Mar 11, 2010 at 23:53 UTC

    ++, nice idea.  Here's a variation of your approach, making use of the postprocess option:

    #!/usr/bin/perl -l use File::Find; my @dirs; find( { wanted => sub {}, postprocess => sub { push @dirs, $File::Find::dir if index $dirs[-1]||"", $File::Find::dir; }, }, '/tmp/a' ); print for @dirs;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-08-23 20:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (178 votes), past polls