Why doesn't Perl file glob() work outside of a loop in scalar context?

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-04-13T21:44:11Z Indexed on 2010/04/13 22:03 UTC
Read the original article Hit count: 397

Filed under:
|
|

According to the Perl documentation on file globbing, the <*> operator or glob() function, when used in a scalar context, should iterate through the list of files matching the specified pattern, returning the next file name each time it is called or undef when there are no more files.

But, the iterating process only seems to work from within a loop. If it isn't in a loop, then it seems to start over immediately before all values have been read.

From the Perl docs:

In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted.

http://perldoc.perl.org/functions/glob.html

However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out.

http://perldoc.perl.org/perlop.html#I/O-Operators

Example code:

use warnings;
use strict;

my $filename;

# in scalar context, <*> should return the next file name
# each time it is called or undef when the list has run out

$filename = <*>;
print "$filename\n";
$filename = <*>;      # doesn't work as documented, starts over and
print "$filename\n";  # always returns the same file name
$filename = <*>;
print "$filename\n";

print "\n";

print "$filename\n" while $filename = <*>; # works in a loop, returns next file
                                           # each time it is called

In a directory with 3 files...file1.txt, file2.txt, and file3.txt, the above code will output:

file1.txt
file1.txt
file1.txt

file1.txt
file2.txt
file3.txt

Note: The actual perl script should be outside the test directory, or you will see the file name of the script in the output as well.

Am I doing something wrong here, or is this how it is supposed to work?

© Stack Overflow or respective owner

Related posts about perl

Related posts about glob