PDA

View Full Version : Newbie attempting a perl script


brad211987
10-23-2006, 11:38 PM
I am new to perl, and am writing a script that takes a directory as an argument and prints the files in that directory and their corresponding file size. My problem is, the output is behaving randomly, at least it seems. when ran with the argument as the directory that the script is located in, it works, but if I give it another directory, it doesnt work for most files, it will work for the current and parent directory, and it will work for .pl files sometimes.

Here is the script:
#!/usr/bin/perl

use warnings;

$dir = shift @ARGV;

opendir MYDIR, $dir;
@files = readdir MYDIR;
closedir MYDIR;

foreach $listitem ( @files )
{
$filesize = -s $listitem;

print $filesize if defined $filesize;
print $listitem,"\n";
}

Does anyone see any problems in this? I am still working on it but am feeling a little lost at the moment.

FishMonger
10-24-2006, 12:27 AM
readdir returns the filename without the path info, so you need to add the path when you check the filesize. Another optin is to use the diamond operator instead of readdir. I didn't add the proper error checking/handling, but here's a revised version.

#!/usr/bin/perl

use warnings;

$dir = shift @ARGV;

foreach $listitem ( <$dir/*> )
{
$filesize = -s $listitem;

print $filesize if defined $filesize;
print $listitem,"\n";
}

brad211987
10-24-2006, 12:30 AM
Awesome, that fixed the entire thing, thank you very much!

ralph l mayo
10-24-2006, 12:46 AM
I was going to help with this but I got distracted trying to golf it ;)

Anyone got better than 43 characters, working with or without passing a path with a trailing slash?

FishMonger
10-24-2006, 01:11 AM
perl -e 'print -s."\t$_\n" for </etc/*>'

ralph l mayo
10-24-2006, 01:20 AM
But that doesn't take any passed path :[

I had
($d=shift)=~s/\/$//;print-s,"$_\n"for<$d/*>

but it doesn't look like it has enough punctuation in it to be optimal

FishMonger
10-24-2006, 01:39 AM
Since we're executing it on the command line, your version only adds unneeded code. If you're going to pass path info, just put it directly in the diamond operator which saves the effort of doing the $d assignment and the regex.

KevinADC
10-24-2006, 03:13 AM
one liners don't help newbies too much though.

ralph l mayo
10-24-2006, 08:33 PM
one liners don't help newbies too much though.

Sure it does, TMTOWTDI and all that.