DeusVult has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone tell me why the following code does what it does?
#!/usr/bin/Perl -w use strict; my $x; while ( $x = <hello there how are you> ) { print "$x\n"; }
If you run this code, the result is:
hello there how are you
Now, the question is, why?

We live in a society exquisitely dependent on science and technology, in which hardly anyone knows anything about science and technology.
- Carl Sagan

Replies are listed 'Best First'.
Re: Sort of like a file handle, but not
by bikeNomad (Priest) on Aug 21, 2001 at 22:41 UTC
    You're calling glob, which expands file name arguments. Since they're unquoted, each of the "file names" is returned to you separately. Your code is equivalent to:
    my $x; while (defined($x = CORE::GLOBAL::glob('hello there how are you', 0))) + { print "$x\n"; }
    Had you had wildcards in there, they would have been expanded as well.
      Leading to shell fun and games like the following, which (at least on 5.005) works on Linux but not on Windows...
      print map "$_\n", glob("{A,B}{a,b}");
      Ah well, I guess non-portability is what I get for being clever. :-(
        Actually globbing is one of the most unportable things on unix. The way perl solves this is by calling /bin/csh with your glob and passes you the result. This is also why globbing CANT work while working under Taint mode...

        T I M T O W T D I

        I beg to differ (about Windows). Run this at a command prompt:

        C:\> perl -e "print map( \"$_\n\", glob(\"{A,B}{a,b}\"))"

        For this particular example, I get identical results on Windows to that on UNIX. Note that Windows' braindead command line quote handling, or lack thereof, requires escaping the double quotes in the perl code and surrounding the entire thing with double quotes

        Under Windows, each executable must do its own command-line globbing, Perl, like any Windows executable must then expand wildcards on its command line, which it seems to do by calling the standard Microsoft __setargv routine, which is far less powerful than even csh in terms of globbing.

        On the other hand, the internal glob() routine is implemented specially for Windows, to behave like a UNIX shell. At least it is in ActiveState's Perl.

        Cheers,
        dmm

        Just call me the Anti-Gates ...