List Directories Examples in Perl
Jump to navigation
Jump to search
List Directories 1
#!/usr/bin/perl
# Derek Winterstien
# Tue May 24 09:16:19 CDT 2005
$dirname = "/home";
opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
while (defined($file = readdir(DIR))) {
if ( -d "$dirname/$file" ) {
print "$dirname/$file is a directory\n";
}
}
closedir(DIR);
List Directories 2
#!/usr/bin/perl
# Derek Winterstien
# Tue May 24 09:16:19 CDT 2005
$dirname = "/home";
opendir(DIR,$dirname) or die "Can't open the current directory: $!\n";
@names = readdir(DIR) or die "Unable to read current dir:$!\n";
closedir(DIR);
foreach $file (@names) {
next if ($file eq "."); # skip the current directory entry
next if ($file eq ".."); # skip the parent directory entry
if (-d "$dirname/$file"){ # is this a directory?
print "found a directory: $file\n";
next; # can skip to the next name in the for loop
}
if ($file eq "core") { # is this a file named "core"?
print "found one!\n";
}
print ".\n";
}
List Directories 3
#!/usr/bin/perl $path=shift || "."; # Get path from command line, or default to . opendir (DIR, $path) or die "could not open directory"; @dirs = grep (!/^\.\.?$/ && (-d "$path/$_"), readdir(DIR)); close (DIR); print "I found these dirs: @dirs\n";