Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://828145]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2018-01-24 02:44 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (255 votes). Check out past polls.