Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 848
Fulvio Scapin Avatar asked Oct 28 '09 23:10

Fulvio Scapin


2 Answers

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')
like image 72
dlowe Avatar answered Oct 24 '22 05:10

dlowe


This is invoking glob.

like image 27
Sinan Ünür Avatar answered Oct 24 '22 05:10

Sinan Ünür