Permalink
Browse files

explain item context and list-(non)-flattening

  • Loading branch information...
moritz committed Nov 4, 2011
1 parent 5738d87 commit a784c6817904d7e08f2a612cf1d7af1db629c11b
Showing with 38 additions and 2 deletions.
  1. +36 −0 answers.md
  2. +2 −2 questions
View
@@ -40,3 +40,39 @@ In Perl 6, many basic types are immutable, but the variables holding them are
not. The `s///` operator works on a variable, into which it puts a newly
creates string object. Likewise `$i++` works on the `$i` variable, not
just on the value in it.
+
+## What's up with array references and automatic derferencing? Do I still need
+the `@` sigil?
+
+In Perl 6, nearly everything is a reference, so talking about taking
+references doesn't make much sense. Unlike Perl 5, scalar variables
+can also contain arrays directly:
+
+ my @a = 1, 2, 3;
+ say @a; # 1, 2, 3
+ say @a.WHAT; # Array()
+
+ my $scalar = @a;
+ say $scalar; # 1, 2, 3
+ say $scalar.WHAT; # Array()
+
+The big difference is that arrays inside a scalar variable do not flatten in
+list context:
+
+ my @a = 1, 2, 3;
+ my $s = @a;
+
+ for @a { ... } # loop body executed 3 times
+ for $s { ... } # loop body executed only once
+
+ my @flat = @a, @a;
+ say @flat.elems; # 6
+
+ my @nested = $s, $s;
+ say @nested.elems; # 2
+
+You can force flattening with `@( ... )` or by calling the `.list` method
+on an expression, and item context (not flattening) with `$( ... )`
+or by calling the `.item` method on an expression.
+
+`[...]` array literals do not flatten into lists.
View
@@ -1,11 +1,10 @@
Language features/builtins
-* how do you take a reference to an array?
* what's the point of the @ and % sigils when you don't need to explicitly
dereference array refs? if my $x = (0, 1); say $x[0] works, why use @x
instead?
* are Perl 6 threads better than Perl 5 threads?
-* does Perl 6 have coroutines
+* does Perl 6 have coroutines?
Meta:
@@ -18,3 +17,4 @@ ANSWERED:
* how do I extract the eigenstates from a junction?
* if Str is immutable, how does s/// work? if Int is immutable, how does $i++
work?
+* array references and list/item context

0 comments on commit a784c68

Please sign in to comment.