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

Re: List constructors

Thread Previous
Larry Wall
March 9, 2005 09:39
Re: List constructors
Message ID:
On Wed, Mar 09, 2005 at 05:56:25PM +0200, wolverian wrote:
: Hi all,
: reading [AS]02 left me a bit unclear on list construction. Specifically,
: as comma still seems to be the list constructor, what do these produce:
:     my $a       = (1, 2);   # a List object of 1, 2?

Same as

    my $a       = [1, 2];

though I'd call in an anonymous array object.  I tend to use List to
mean the lazy internal data structure that hasn't yet been bound to
formal parameters, so it doesn't even know yet which of its arguments
might be taken in scalar or list context.  By the time the assignment
happens above, it knows the whole list is in scalar context, and the
scalar comma implies the existence of [...] around it.

:     my $a       = (1);      # Int 1?

Same as:

    my $a = 1;

:     my $a       = (1,);     # List of 1?

    my $a = [1];

:     my ($a)     = (1, 2);   # Int 1? Or does it need *?

List assignment works as in Perl 5 so the 2 is discarded silently, so
yes, you end up with 1 in $a.  You only need * when you're using := to
do binding (or the equivalent parameter binding of functions/methods).

:     my ($a,)    = (1, 2);   # Same as above, I hope...


:     my ($a, $b) = (1);      # $a == 1, I presume

Just like Perl 5.

: Also what do these rather esoteric cases do:
:     my ()   = ();

I expect the compiler could reasonably either complain or optimize it
away.  If the right side has side effects:

    my () = (foo())

it could be reduced to


:     my $a   = ();
:     my ($a) = ();

Same as Perl 5.

: Syntax errors in a few of those are welcome. :)

Depends on whether you want the edge cases to complain or DWIM with
stupid code that is spit out by a code generator.  A person would never
write my () = (), but a code generator might very well.  On the other
hand, if someone has a defective text macro, then

    my (fancy_stuff($a,$b,$c)) = (fancy_stuff($x,$y,$z));

might reduce to

    my () = ()

and that would be a difficult kind of error to catch.  Well, maybe not,
since you'd notice undefined variables pretty quickly...

Anyway, I'd lean toward not complaining on such, or maybe just issuing
a warning, which the code generator can suppress if it likes.  I put
it in the same category as "Useless use of ... in a void context".


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