in reply to Dir Tree in Perl

PerlMonks mangled my source code because it contained non-ASCII characters. So I've posted to github instead...

https://gist.github.com/4011150

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Dir Tree in Perl
by Hopfi (Novice) on Nov 04, 2012 at 18:18 UTC
    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);
      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". ;-)