Telemachus Odysseos wrote:
Hi,
Hello,
I have read around and cannot seem to find an answer to this, and it's driving me a bit nuts. I have a small script that I am trying to use to list the items in a directory and the size of the items. The script works perfectly if I run it in the directory itself, but if the script is somewhere else in my system, it prints the filenames but not the sizes. I have tried changing ownership of the perl script every which way (thinking it's a permissions problem), but even if the script is owned by root, no joy. Here is the script. Any ideas would be greatly appreciated: #!/usr/bin/perl opendir(CD,"/path/to/directory/here");
You should *ALWAYS* verify that the directory opened correctly: opendir CD, '/path/to/directory/here' or die "Cannot open '/path/to/directory/here' $!";
while ( $_ = readdir(CD)) { next if $_ eq "." or $_ eq ".."; print $_, " " x (30-length($_)); print (-s $_ ); print "\n"; }
As it states in the documentation for readdir(): perldoc -f readdir readdir DIRHANDLE Returns the next directory entry for a directory opened by "opendir". If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns an undefined value in scalar context or a null list in list context. If you’re planning to filetest the return values out of a "readdir", you’d better prepend the directory in question. Otherwise, because we didn’t "chdir" there, it would have been testing the wrong file. opendir(DIR, $some_dir) || die "can’t opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR); closedir DIR; So you need code something like: #!/usr/bin/perl use warnings; use strict; my $dir = '/path/to/directory/here'; opendir CD, $dir or die "Cannot open '$dir' $!"; while ( my $entry = readdir CD ) { next if $entry eq '.' or $entry eq '..'; printf "%-30s%d\n", $entry, -s "$dir/$entry"; } closedir CD; 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/