Re: perl syntax oddity

Ilmari Karonen <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <[email protected]>
Yitzchak Scott-Thoennes wrote:
 >
> Can anyone give a justification why this should work as it does (or a
> reasonable use):
> 
> $ perl -wle'sub getaglob {*loopvar} for ${&getaglob} (qw/the owl and the pussyc
> at/) { print $loopvar }'

Well, why not?  After all, it works everywhere else:

   sub getaglob {*foo}

   $foo = "beep\n";
   print ${&getaglob};

What's weird is that the more conventional way -- using references -- 
does _not_ work in for() loops:

   sub getaref {\$foo}
   for ${&getaref} (qw/one two three/) {print "$foo\n"}

fails with "Not a GLOB reference".  The other way around it works:

   sub getaref {\$foo}
   for $foo (qw/one two three/) {print "${&getaref}\n"}

I guess it's because for() localizes the variable it's iterating over, 
and needs the glob for that.  Oddly enough, however, local() does not 
accept a glob that way:

   sub getaglob {*foo}
   $foo = "pong\n";
   for ${&getaglob} ("ping ") { print $foo }
   print $foo;

works, printing "ping pong", while:

   sub getaglob {*foo}
   $foo = "pong\n";
   { local ${&getaglob} = "ping "; print $foo }
   print $foo;

fails with "Can't localize through a reference"!

Weird.

-- 
Ilmari Karonen
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.