Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

explain item context and list-(non)-flattening

  • Loading branch information...
commit a784c6817904d7e08f2a612cf1d7af1db629c11b 1 parent 5738d87
Moritz Lenz moritz authored

Showing 2 changed files with 38 additions and 2 deletions. Show diff stats Hide diff stats

  1. +36 0 answers.md
  2. +2 2 questions
36 answers.md
Source Rendered
@@ -40,3 +40,39 @@ In Perl 6, many basic types are immutable, but the variables holding them are
40 40 not. The `s///` operator works on a variable, into which it puts a newly
41 41 creates string object. Likewise `$i++` works on the `$i` variable, not
42 42 just on the value in it.
  43 +
  44 +## What's up with array references and automatic derferencing? Do I still need
  45 +the `@` sigil?
  46 +
  47 +In Perl 6, nearly everything is a reference, so talking about taking
  48 +references doesn't make much sense. Unlike Perl 5, scalar variables
  49 +can also contain arrays directly:
  50 +
  51 + my @a = 1, 2, 3;
  52 + say @a; # 1, 2, 3
  53 + say @a.WHAT; # Array()
  54 +
  55 + my $scalar = @a;
  56 + say $scalar; # 1, 2, 3
  57 + say $scalar.WHAT; # Array()
  58 +
  59 +The big difference is that arrays inside a scalar variable do not flatten in
  60 +list context:
  61 +
  62 + my @a = 1, 2, 3;
  63 + my $s = @a;
  64 +
  65 + for @a { ... } # loop body executed 3 times
  66 + for $s { ... } # loop body executed only once
  67 +
  68 + my @flat = @a, @a;
  69 + say @flat.elems; # 6
  70 +
  71 + my @nested = $s, $s;
  72 + say @nested.elems; # 2
  73 +
  74 +You can force flattening with `@( ... )` or by calling the `.list` method
  75 +on an expression, and item context (not flattening) with `$( ... )`
  76 +or by calling the `.item` method on an expression.
  77 +
  78 +`[...]` array literals do not flatten into lists.
4 questions
... ... @@ -1,11 +1,10 @@
1 1 Language features/builtins
2 2
3   -* how do you take a reference to an array?
4 3 * what's the point of the @ and % sigils when you don't need to explicitly
5 4 dereference array refs? if my $x = (0, 1); say $x[0] works, why use @x
6 5 instead?
7 6 * are Perl 6 threads better than Perl 5 threads?
8   -* does Perl 6 have coroutines
  7 +* does Perl 6 have coroutines?
9 8
10 9 Meta:
11 10
@@ -18,3 +17,4 @@ ANSWERED:
18 17 * how do I extract the eigenstates from a junction?
19 18 * if Str is immutable, how does s/// work? if Int is immutable, how does $i++
20 19 work?
  20 +* array references and list/item context

0 comments on commit a784c68

Please sign in to comment.
Something went wrong with that request. Please try again.