http://www.perlmonks.org?node_id=972634


in reply to Re^2: listing all subdirectories of directory into file
in thread listing all subdirectories of directory into file

At first I thought File::Find might not be that good for this, because he wants to make a list within each directory of its subdirectories, which at first glance means "looking at" each directory twice: once when you're adding it to its parent directory's list, and then again when File::Find comes across it. But then I thought of this, which is very simple, but has the downside of opening the output file every time it needs to write a line:

#!/usr/bin/env perl use Modern::Perl; use File::Find; sub w { if( -d $_ ){ open my $out, '>>', 'list' or die $!; print $out "$_\n"; close $out; } } File::Find::find(\&w, '.');

Aaron B.
Available for small or large Perl jobs; see my home node.

Replies are listed 'Best First'.
Re^4: listing all subdirectories of directory into file
by jdrago999 (Pilgrim) on Jun 08, 2012 at 17:23 UTC

    Why open and close $out every time?

    #!/usr/bin/env perl use Modern::Perl; use File::Find; # $out is used within w(): open my $out, '>>', 'list' or die $!; sub w { if( -d $_ ){ print $out "$_\n"; } } File::Find::find(\&w, '.');

      If you look at his spec, he wants more than one "out" file. In each directory, he wants a file named 'list' that contains a list of every subdirectory of that directory. So in a directory structure like the following, you would get 'list' files like so:

      $ find . -ls|cut -b14-24,68- drwxr-xr-x . drwxr-xr-x ./a -rw-r--r-- ./a/list drwxr-xr-x ./a/d drwxr-xr-x ./a/c drwxr-xr-x ./b -rw-r--r-- ./list $ cat list a b $ cat a/list c d

      Aaron B.
      Available for small or large Perl jobs; see my home node.