Does the Perl diamond operator iterate over non-magic arrays (not @ARGV)?

693 views Asked by At

I don't think the following should work, but it does:

$ perl -e '@a = qw/1222 2 3/; while (<@a>) { print $_ ."\n";}'
1222
2
3
$

As far as I know, Perl's <> operator shoud work on filehandle, globs and so on, with the exception of the literal <> (instead of <FILEHANDLE>), which magically iterates over @ARGV.

Does anyone know if it's supposed to work also as it did in my test?

3

There are 3 answers

2
dlowe On BEST ANSWER

Magic at work!

From 'perldoc perlop':

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context.

This is the rule you're triggering with this code. Here's what's happening:

  1. <@a> is (syntactically, at compile-time) determined to be a glob expansion
  2. thus <> turns @a into the string "1222 2 3" (string interpolation of an array)
  3. glob("1222 2 3") in list context returns ('1222', '2', '3')
4
Robert Massaioli On

<FH> is not the name of a filehandle, but an angle operator that does a line-input operation on the handle. This confusion usually manifests itself when people try to print to the angle operator" - Programming Perl

So in your case the array is a handle, which makes sense, and thus the operator iterates over it. So in answer to your question, yes, I think this is standard (but obscure) Perl. It is obscure because the language has more obvious ways to iterate over an array.

P.S. However, thanks for this, this will be great for code golf competitions.

0
Sinan Ünür On

This is invoking glob.