develooper Front page | perl.perl6.language | Postings from May 2005

Re: (1,(2,3),4)[2]

Thread Previous | Thread Next
May 18, 2005 15:50
Re: (1,(2,3),4)[2]
Message ID:
"TSa (Thomas SandlaƟ)" skribis 2005-05-18 21:54 (+0200):
> Juerd wrote:
> >>	my @b = [1,2,[3,4]];
> >>	is(+@b, 1, 'Array length, nested [], outer []s');
> Isn't that a bit inconvenient? To get e.g. 2 out of @b
> one has to write @b[0][1] while for $b a $b[1] suffices.

Parens and square brackets are very different things.

The above is more commonly written as

    my @b = ([1,2,[3,4]);

Having arrayrefs flatten in list context, or having [] to be able mean
something other than constructing an arrayref, is a change that requires
the very fundaments of Perl to change very heavily, beginning by
eliminating lists entirely, and using only arrays.

I believe I said it before, but I'll do it again: Perl is not Python.
Just that the two languages are both powerful, and both begin with a P,
and in some respects even syntactically look like eachother (hey, that's
what we get for loving ASCII), doesn't mean any theory applicable to one
automatically makes sense for the other.

> And @x = @b maintains this superficial level of indirection?

ARRAY = LIST is the syntax for assigning to an array. Note that the RHS
is list context, not Array context.

> Does @x = @b[] remove one level? How does that compare

No. As far as I know, @b[] and @b are the synonymous.

> my @b = (1,2,[3,4]);
> is equivalent to
> my $b = [1,2,[3,4]];

No, that's not equivalent. $b contains a reference to an array, while @b
itself is an array.

Hoping the box diagram worked the last time, I'll try again:

     +-- @b         +-- $b            (this array has no name;
     |              |                  it is "anonymous")
     V              V
    +----------+   +------------+    +----------+
    | elements |   | reference ----> | elements |
    +----------+   |------------+    +----------+
    ARRAY          SCALAR            ARRAY

> which in turn is equivalent to
> my $b = (1,2,[3,4]);

That is only because the comma operator is in scalar context. The parens
here merely GROUP, for precedence. my $b = eval "1,2,[3,4]" would be
exactly the same. Just to show you the parens are NOT constructors of
the list.

> $b = @b

No, that assigns a *reference to $b* to @b, without any copying of

> Am I insane?

No, you just STILL can't cope with Perl's notion of names, containers
and values, and you don't realise that () and [] are not related, more
specifically: that () has absolutely nothing to do with arrays or lists.

These are mistakes many Perl 5 beginners make, especially those coming
from Python.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About