PDA

View Full Version : opendir function in PERL


boredcrazy
03-27-2001, 12:22 AM
I've written the following "Hello World" program to list all the
files in my main directory. But, when I run it, it shows that my folder is
empty when it's clearly not.

My account name is napkin. Is the path correct?

What am I doing wrong?

# # # # # # # # # # # # # # # # # # # # # # # #




#!/usr/bin/perl

#I'm assuming this is
#where I am on the server.
$PathToLiveFolder = "/home/napkin/public_html/";

#Open the main folder and split
#the file names into an array
opendir (WWW, $PathToLiveFolder);
@filenames = readdir (WWW);
closedir (WWW);

#Print HTTP_Header and intro line
print "Content-type: text/html\n\n";
print "All the files and folders should be listed here.<br>";

#Print out the name of each file in the array
$x = 0;
while($x < @filenames)
{
print "-".$filenames[$x]."<br>";
$x++;
}

#Display file count
print "<br>There were this many files:".@filenames;

Stimpy
03-30-2001, 01:55 AM
I would do it this way:

#Print out the name of each file in the array
$x = 0;

foreach $FileName(@filenames)
{
print "-".$FileName."<br>";
$x++;
}

I think.

Himself
04-08-2001, 06:25 PM
coupla tips crazy:

1. Use the $! variable in perl. that prints out any error message that perl generates.

2. enclose all executes in an if statement. EX:
if (opendir (WWW, $PathToLiveFolder))
{
print "directory open success";
# execute file list print here
}
else
{
print "dir open failed, reason was $!";
}
this way when the open fails you'll know why.

JohnM
04-20-2001, 02:04 AM
or better written:


#Print out the name of each file in the array
foreach (@filenames) {
print '-',$_,'<br>';
}

JohnM
04-20-2001, 02:05 AM
or even better:


#Print out the name of each file in the array
print '-',$_,'<br>' foreach (@filenames);

JohnM
04-20-2001, 02:10 AM
full script:


#!/usr/bin/perl -wT
use strict;
use CGI qw/:standard/;
my $PathToLiveFolder = "/home/napkin/public_html/";

opendir GETFILES, $PathToLiveFolder or die "Couldn't opendir $PathToLiveFolder: $!";
print header, 'All the files and folders should be listed here.<br>';
my @tmp = readdir(GETFILES);
foreach my $dirname (@tmp) {
print "-$dirname<br>\n"
}
closedir GETFILES;
print '<br>There are ', scalar(@tmp), ' files.';