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

Re: tree command

by RichardK (Parson)
on Oct 13, 2015 at 10:49 UTC ( #1144672=note: print w/replies, xml ) Need Help??

in reply to tree command

You're iterating over the list of files twice, once in the grep & once in the foreach, and you don't need to do that. Also glob is easier to use than opendir/readdir, IMHO. So you could have done something like this

use v5.20; use warnings; use autodie qw/:all/; use File::Glob qw/:bsd_glob/; use File::Spec; use File::Basename; sub showtree { my ($dir,$indent) = @_; $indent .= ' '; my @list = bsd_glob(File::Spec->catfile($dir,'*')); foreach my $f (@list) { if (-d $f) { say $indent,'+-',basename($f); showtree($f,$indent . '|'); } if (-l $f) { say $indent,'+-',basename($f),' --> ',readlink($f); } } } showtree($ARGV[0] // '.');

Replies are listed 'Best First'.
Re^2: tree command
by Skeeve (Parson) on Oct 13, 2015 at 11:43 UTC

    I'm iterating twice because I need to find the number of entries first. That way I know when to finish the (sub-)tree.


      No, you can know the length of the list and still only process it once. The two things aren't related at all.

        Okay. So would you mind telling me how I could filter out:

        • hidden files and directories (okay - "glob")
        • files

        without iterating over the content of the directory and know in advance that the last 3 items in my list don't count?

        Example: I have in my list [ a b c d e ] where b, d and e are files, which I do not want to display, while a and c are the directories to show. How would I know that in advance?

        With my approach I filter b, d and e out, leaving me with just [ a c ]. So I know that after "c" there won't be any more files or directories to be displayed.

        How would you achieve this?


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2020-06-05 01:03 GMT
Find Nodes?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?

    Results (35 votes). Check out past polls.