LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   PERL can't read contents of directory. (https://www.linuxquestions.org/questions/linux-newbie-8/perl-cant-read-contents-of-directory-672338/)

knockout_artist 09-25-2008 12:16 PM

PERL can't read contents of directory.
 
Hi,

here is the code

Code:


use Cwd;
$DIRNAME =  "/tmp/etc";


open(DIR, $DIRNAME) or die "cant open  $DIRNAME";

my @name = readdir(DIR)    or die "can't read whats in the dir $DIRNAME\n";

foreach my $name (@name){
if (-d $name){
print "dir found \n";
}

}

closedir(DIR);

I do have files/dir in side /tmp/etc but above code is unable to read it.

Thanks

chrism01 09-25-2008 08:16 PM

1. use opendir : http://perldoc.perl.org/functions/opendir.html
In Unix things look like files, but a dir not same as a file

2. When using open, close, opendir, closedir, always use

opendir(DIR, $DIRNAME) or die "cant open $DIRNAME: $!";

$! = error msg supplied by Perl


Always use warnings and strict eg

#!/usr/bin/perl -w
use strict; # Enforce declarations


they'll save you a lot of stress later. You can syntax check a prog without running it using
perl -wc file.pl


All times are GMT -5. The time now is 07:04 PM.