MK wrote:
i am trying to create a perl routine to traverse directories (like a
file browser) that will be incorporated into a more specific framework,
but for some incomprehensible (to me) reason, opendir will not produce
correct information when called in a sub!!! Why (the exact same script
works fine -- once, obviously -- without the sub loop)?
#!/usr/bin/perl
# move thru directories
use warnings;
When I compile your code I get some warnings:
$ perl -c dirmenu.pl
Name "main::ND" used only once: possible typo at dirmenu.pl.tdy line 19.
Name "main::dirlist" used only once: possible typo at dirmenu.pl.tdy
line 30.
Name "main::chuck" used only once: possible typo at dirmenu.pl.tdy line 40.
dirmenu.pl syntax OK
#use strict;
You shouldn't disable the strict pragma.
use File::stat;
Based on your code, you don't really need this module.
sub listdir {
$dir = $_[ 0 ];
opendir( D, "$dir" );
perldoc -q quoting
Found in /usr/share/perl/5.8/pod/perlfaq4.pod
What's wrong with always quoting "$vars"?
You should always verify system calls like opendir() completed
successfully. You should probably also use lexically scoped directory
handles:
opendir my $D, $dir or die "Cannot opendir '$dir' $!";
@list = readdir( D );
my @list = readdir $D;
closedir $D;
contentof();
selecta();
}
sub selecta {
print "\nwhich directory (#): ";
$new = <>;
User input from STDIN will have a trailing newline so you have to
chomp() it:
chomp( $new = <> );
closedir( ND );
The directory handle ND has not been opened so why are you closing it?
listdir( $new );
}
sub contentof {
opendir( D, "$dir" );
perldoc -q quoting
Found in /usr/share/perl/5.8/pod/perlfaq4.pod
What's wrong with always quoting "$vars"?
You should always verify system calls like opendir() completed
successfully. You should probably also use lexically scoped directory
handles:
opendir my $D, $dir or die "Cannot opendir '$dir' $!";
@list = readdir( D );
my @list = readdir $D ;
closedir $D;
$num = 0;
foreach $file ( @list ) {
if ( -d $file ) {
-d looks for $file in the current directory but the file name is
actually in "$dir/$file".
print "$num: $file\n";
$dirlist[ $num ] = $file;
$num++; # increment $num
It would be simpler just to use push():
push @dirlist, $file;
}
}
}
$dir = $ARGV[ 0 ]; # stat (eg) won't deal w/ @ARGV
What makes you think that stat() won't deal with @ARGV?
print "directory $dir --\n";
contentof();
closedir( D );
You should put closedir() in the scope that it is opened instead of at
file scope.
$chuck = <>; # deals with a strange extra stdout->stdin return
If you don't need the variable $chuck then you can just use void context:
<>; # deals with a strange extra stdout->stdin return
selecta();
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/