Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: As usual

by Tyke (Pilgrim)
on Mar 01, 2001 at 19:49 UTC ( #61573=note: print w/replies, xml ) Need Help??

in reply to As usual
in thread Recursive directory scanning

You're looping on the first item in the list which will be a '.'

Works better if you add next if $item eq '.' or $item eq '..'; after the foreach

readdir gives you the names in the directory... not path names, so when you call the printdir recursively you'll need to prefix the current directory to each element of the list. (Naturally you'll need to change your '.' test accordingly.

Anyway this seems to work on my machine.

#!perl -w
use strict;
use Carp;


sub printdir {
    my $item;
    foreach $item(@_) {
      next if $item =~ /\.{1,2}$/;
      if (-d $item) {
        print "$item\n";
        opendir(SUBDIR, $item) or croak "Can't open directory :$!";
        my @subdir_items = readdir(SUBDIR);      #+
        closedir(SUBDIR);                        #+  
        printdir(map {"$item/$_"}@subdir_items); #+

Oh, by the way the equivalent in my previous post should have been

perl -Mstrict -MFile::Find -wle 'find sub{print $File::Find::dir if -d},@ARGV' .
but you saw that already, didn't you :)

Update: Just saw merlyn's post. The above ran on Win32 because (as he says) the Windows port recognizes forward slashes as valid directory separators. I don't know whether this is an issue on other non unix ports. Still, I agree with him, it's a lot safer here to stay with the standard.

Update 2: The '.' test is broken: it will match any file ending with a '.'. You'd need to split off the file name from the path, so you might as well use File::Spec... Oh good grief, why did I ever post this code? This'll teach me to shut up :(

Replies are listed 'Best First'.
by pwhysall (Acolyte) on Mar 01, 2001 at 21:19 UTC
    This regex, I think, will match . or .. and nothing else:


      Good thing you're just "thinking". It also matches ".\n" and "..\n", thanks to $'s little-understood feature of matching before the optional newline at the end of the string.

      Perhaps you want


      -- Randal L. Schwartz, Perl hacker

      This is true, and that would break the script :(

      Remember that $item has been prefixed by the directory, so we want to filter out elements like foo/bar/. and fi/fo/fum/..

      Better would be to extract the file name and compare it to current/parent directory in a portable fashion. this will work on *nix or windows. I have no idea what it might do on a MAC or on VMS.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2023-01-30 19:18 GMT
Find Nodes?
    Voting Booth?

    No recent polls found