in reply to Re: Dir Tree in Perl
in thread Dir Tree in Perl

ok got it done. i didnt use tree because im trying to avoid using cpan for this project. heres the code if someones interested:
#!/usr/bin/perl ($dir) = @ARGV; open (MYFILE, '>>data.txt') || die; &loopDir($dir, ""); exit; sub loopDir { $dir = "." unless $dir; local($dir, $margin) = @_; chdir($dir) || die "Cannot chdir to $dir\n"; local(*DIR); opendir(DIR, "."); while ($f=readdir(DIR)) { next if ($f eq "." || $f eq ".."); print MYFILE "$margin$f\n"; if (-d $f) { &loopDir($f,$margin." "); } } closedir(DIR); chdir(".."); } close (MYFILE);

Replies are listed 'Best First'.
Re^3: Dir Tree in Perl
by afoken (Chancellor) on Nov 04, 2012 at 21:16 UTC
    im trying to avoid using cpan for this project

    Bad idea. Your code is also sub-optimal:

    • use strict missing
    • & in front of function calls does not do what you think. Get rid of it, this ain't ancient Perl 4.
    • local instead of my
    • Recursion in loopDir will eventually run out of handles. Collect all subdirectories, then recurse after closing the directory handle. Or use a directory queue (shift the directory to read from, push every new directory found, run until queue is empty) and completely get rid of the recursion.
    • close (MYFILE) is unreachable due to exit in front of it
    • Two-argument open instead of three-argument open. Do you really need to support perl < 5.6 (more than twelve years old)?
    • Bareword file handles instead of lexical ones
    • open || die instead of open or die, same problem with chdir
    • die without an error message ($!)
    • opendir lacks an error check.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)