Here's a simple perl script where I am listing out the contents of a
directory. When it completes, the following error occurs. How do I
eliminate this?
Use of uninitialized value in length at C:\BegPerl\deldir.pl line 23.
Below is the script:
#!/usr/bin/perl
# Dsrch1.plx
# use strict ;
If you comment out strictures they can't help you. Don't accept this shortcut while learning, it teaches the wrong things. Turn it on.
use warnings ;
$directory = $ARGV[0];
my $directory = $ARGV[0];
opendir(DIR, $directory) or die "Can't open $directory\n" ;
Include $! in the error message so that you will know why it can't be opened.
$direntry = readdir(DIR);
You are only reading the first entry in the directory handle. You need to put this in list context, presumably with an array, to read them all.
my @list = readdir(DIR);
($mtime) = stat($direntry);
'mtime' is not the first element of the list returned by stat. You want the 9th.
($mtime) = (stat $direntry)[9];
And presumably you want to do this in your loop.
####################################################### # read entire directory contents and print out # ####################################################### while (length($direntry) > 0) {
$direntry only contains the first value so this loop is pointless, see the list comment above. And using length is probably not necessary, since you can just use definedness to test for an entry since you won't ever have an empty string directory.
foreach my $file (@list) {
print "$direntry - modify date: $mtime\n" ; $direntry = readdir(DIR);
Now I see how you are doing your loop. The problem is that at the end of the directory list, readdir returns undef, which is why you are getting the warning about an uninitialized value. The loop runs, asks for the next entry in the list, there aren't any more, then the loop does its check again, on the empty value.
If you want to retrieve the entries one at a time (and large directory lists could benefit from this) you can do the readdir in the while test,
while (my $file = readdir DIR) {
Which will bail when it hits the end of the list.
}
closedir(DIR);
use strict; use warnings;
my $DIRHANDLE; opendir $DIRHANDLE, "$ARGV[0]" or die "Can't open directory handle: $!";
while (my $file = readdir $DIRHANDLE) { my $mtime = (stat $file)[9]; print "$file - modify date: $mtime\n"; } closedir $DIRHANDLE;
HTH,
http://danconia.org
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>