locked_user TomJerry has asked for the wisdom of the Perl Monks concerning the following question:
This is a very simple test program for traversing a directory.
I got two versions, the only difference is listing a directory --- one uses while(<*>), the other uses foreach(). Both should work.
However, strange things happened. The 1st is always trapped in a infinite looping, while the 2nd works well. Why?
# 1st form sub traverse_file { my $dir = shift; if (-d $dir) { while (<$dir/*>) { traverse_file($_); } } else { print "$dir\n"; } }
# 2nd form sub traverse_file { my $dir = shift; if (-d $dir) { my @subdirs=<$dir/*>; foreach (@subdirs){ traverse_file($_); } } else { print "$dir\n"; } }
| Replies are listed 'Best First'. | |
|---|---|
|
Re: foreach vs. while inside a directory traversing subroutine
by Athanasius (Archbishop) on May 26, 2015 at 04:45 UTC | |
by locked_user TomJerry (Initiate) on May 26, 2015 at 06:25 UTC | |
|
Re: foreach vs. while inside a directory tranversing subroutine
by wrog (Friar) on May 26, 2015 at 03:48 UTC | |
|
Re: foreach vs. while inside a directory tranversing subroutine
by locked_user sundialsvc4 (Abbot) on May 26, 2015 at 11:36 UTC | |
by Anonymous Monk on May 26, 2015 at 12:00 UTC |