SPUG: RE: Simple program - gone wrong

Brett Cundal bcundal at cundal.net
Mon Jul 8 12:53:38 CDT 2002


On Mon, Jul 08, 2002 at 09:58:16AM -0700, Sweethomes wrote:
>     #!/usr/bin/perl
>     open(RDIR,"./admin/data/rdir.txt");
>     opendir(DIR, "../");
>     @files = readdir(DIR);
>     for($num = 0; $num <= 100; $num += 1)
>     foreach $name (@files) {
>     if(-d $name){}elsif($name eq "." || $name eq ".."){}else{
>     print(RDIR, "$num | $name\n");}}
>     close(RDIR);
>     close(DIR);
>     exit;

You've got two nested loops (does this compile at all? I don't htink
you can leave out the curly braces in perl like you can in C)... this
will print out 100 sets of filenames, ie. each file will be listed 100
times in the results. You probably want a single loop instead:

#!/usr/bin/perl
open(RDIR,"./admin/data/rdir.txt");
opendir(DIR, "../");
@files = readdir(DIR);
# Remove:
# for($num = 0; $num <= 100; $num += 1)
# Add:
  $num = 0;
foreach $name (@files) {
if(-d $name){}elsif($name eq "." || $name eq ".."){}else{
print(RDIR, "$num | $name\n");
# Add:
  $num++;
# If you want to break at 100... I'm not sure:
# last if $num >= 100;
}}
close(RDIR);
close(DIR);
exit;

Is that what you're trying to do?

BTW, using elsif instead of negated conditionals makes for excellent
unreadability. :)

-- Brett
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20020708/31573a36/attachment.bin


More information about the spug-list mailing list