title: Why doesn't Perl file glob() work outside of a loop in scalar context?
body: <p>According to the Perl documentation on file globbing, the &lt;*&gt; 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.
  </p>
  
  <p>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.
  </p>
  
  <p>From the Perl docs:
  </p>
  
  <blockquote><i>In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted.
  </i></blockquote>
  
  <p><a href="http://perldoc.perl.org/functions/glob.html" rel="nofollow noreferrer"><a href="http://perldoc.perl.org/functions/glob.html" rel="nofollow noreferrer">http://perldoc.perl.org/functions/glob.html</a></a></p>
  
  <blockquote><i>However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out.
  </i></blockquote>
  
  <p></p></p>
  
  <p>http://perldoc.perl.org/perlop.html#I/O-Operators
  </p>
  
  <p>Example code:
  </p>
  
  <pre>
  use warnings;
  use strict;
  
  my $filename;
  
  # in scalar context, &lt;*&gt; should return the next file name
  # each time it is called or undef when the list has run out
  
  $filename = &lt;*&gt;;
  print "$filename\n";
  $filename = &lt;*&gt;;      # doesn't work as documented, starts over and
  print "$filename\n";  # always returns the same file name
  $filename = &lt;*&gt;;
  print "$filename\n";
  
  print "\n";
  
  print "$filename\n" while $filename = &lt;*&gt;; # works in a loop, returns next file
                                             # each time it is called
  </pre>
  
  <p>In a directory with 3 files...file1.txt, file2.txt, and file3.txt, the above code will output:
  </p>
  
  <pre>
  file1.txt
  file1.txt
  file1.txt
  
  file1.txt
  file2.txt
  file3.txt
  </pre>
  
  <p><i>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.
  </i></p>
  
  <p>Am I doing something wrong here, or is this how it is supposed to work?
  </p>