Abigail on 25 Nov 2003 14:47:17 -0500


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Why can't an array element be used as the index var in foreach?


On Mon, Nov 24, 2003 at 12:13:58AM -0500, Mark Rogaski wrote:
> An entity claiming to be Walt Mankowski (waltman@pobox.com) wrote:
> : 
> : In nearly every other case I can think of in Perl, array elements work
> : just like scalars.  You can, for instance, take references to them and
> : use local on them.  In fact, a reference to an array element says that
> : it's a scalar reference.
> : 
> : So what's so special about foreach loops that array elements aren't
> : permitted?  And if they are explicitly forbidden, where is that
> : documented?
> : 
> 
> Walt,
> 
> I think the limitation has to do with foreach loop index being an alias,
> as opposed to a hard reference.  Being an alias, such a syntax would imply
> something like:
> 
>  *c[0] = 0;
> 
> Setting up such a glob would blow up when you tried to see what was in
> $c[0], because it wouldn't know whether it was a scalar named ${c[0]} or 
> an array element named @{c[0]}.  


No. It doesn't even parse:

    $ perl -wle 'for $c[0] (0) {}'
    syntax error at -e line 1, near "$c["
    Execution of -e aborted due to compilation errors.
    $

Now, this compiles:

    $ perl -wcle 'for ${\$c[0]} (0) {}'
    Name "main::c" used only once: possible typo at -e line 1.
    -e syntax OK
    $

But if you execute it, it gives an error I cannot explain:

    $ perl -wle 'for ${\$c[0]} (0) {}'
    Name "main::c" used only once: possible typo at -e line 1.
    Not a GLOB reference at -e line 1.
    $


Abigail
-
**Majordomo list services provided by PANIX <URL:http://www.panix.com>**
**To Unsubscribe, send "unsubscribe phl" to majordomo@lists.pm.org**