Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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 (Vicar) 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.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      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?


        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2018-07-18 17:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (393 votes). Check out past polls.

    Notices?