diff options
| author | C. Bess <cbess@company.com> | 2015-11-09 17:55:53 -0600 | 
|---|---|---|
| committer | C. Bess <cbess@company.com> | 2015-11-09 17:55:53 -0600 | 
| commit | df0992d72c2a28f140e6ff9681c505f36e19249a (patch) | |
| tree | 508aa3abe4c25b957dca442560d9c95c9b1fc97a /perl6.html.markdown | |
| parent | afc5ea14654e0e9cd11c7ef1b672639d12418bad (diff) | |
| parent | c460e1fafa0e9b4edc6a5cb35b970bb5cc030a81 (diff) | |
Merge remote-tracking branch 'adambard/master'
Conflicts:
	swift.html.markdown
Diffstat (limited to 'perl6.html.markdown')
| -rw-r--r-- | perl6.html.markdown | 558 | 
1 files changed, 272 insertions, 286 deletions
| diff --git a/perl6.html.markdown b/perl6.html.markdown index b178de1e..3eec19f3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1,17 +1,16 @@  --- -name: perl6  category: language  language: perl6  filename: learnperl6.pl  contributors: -    - ["Nami-Doc", "http://github.com/Nami-Doc"] +    - ["vendethiel", "http://github.com/vendethiel"]  --- -Perl 6 is a highly capable, feature-rich programming language made for the -upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for at +least the next hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on +the JVM and [the MoarVM](http://moarvm.com).  Meta-note : the triple pound signs are here to denote headlines,  double paragraphs, and single notes. @@ -35,7 +34,8 @@ my $variable;  ## * Scalars. They represent a single value. They start with a `$`  my $str = 'String'; -my $str2 = "String"; # double quotes allow for interpolation +# double quotes allow for interpolation (which we'll see later): +my $str2 = "String";  # variable names can contain but not end with simple quotes and dashes,  #  and can contain (and end with) underscores : @@ -66,23 +66,13 @@ my @keys = 0, 2;  @array[@keys] = @letters; # Assign using an array  say @array; #=> a 6 b -# There are two more kinds of lists: Parcel and Arrays. -# Parcels are immutable lists (you can't modify a list that's not assigned). -# This is a parcel: -(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error -# This is a list: -my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay! - -# Lists flatten (in list context). You'll see below how to apply item context -#  or use arrays to have real nested lists. - - -## * Hashes. Key-Value Pairs. -# Hashes are actually arrays of Pairs (`Key => Value`), -#  except they get "flattened", removing duplicated keys. +## * Hashes, or key-value Pairs. +# Hashes are actually arrays of Pairs +# (you can construct a Pair object using the syntax `Key => Value`), +#  except they get "flattened" (hash context), removing duplicated keys.  my %hash = 1 => 2,             3 => 4; -my %hash = autoquoted => "key", # keys *can* get auto-quoted +my %hash = foo => "bar", # keys get auto-quoted              "some other" => "value", # trailing commas are okay              ;  my %hash = <key1 value1 key2 value2>; # you can also create a hash @@ -103,7 +93,6 @@ say %hash<key2>;   # If it's a string, you can actually use <>                     # (`{key1}` doesn't work, as Perl6 doesn't have barewords)  ## * Subs (subroutines, or functions in most other languages). -# Stored in variable, they use `&`.  sub say-hello { say "Hello, world" }  sub say-hello-to(Str $name) { # You can provide the type of an argument @@ -112,34 +101,10 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument      say "Hello, $name !";  } -# Since you can omit parenthesis to call a function with no arguments, -#  you need "&" in the name to capture `say-hello`. -my &s = &say-hello; -my &other-s = sub { say "Anonymous function !" } - -# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". -                             # Note: you can have parameters *before* (like here) -                             # a slurpy one, but not *after*. -  say @rest.join(' / ') ~ " !"; -} -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! -                                           # Note that the splat did not consume -                                           #  the parameter before. - -## You can call a function with an array using the -# "argument list flattening" operator `|` -# (it's not actually the only role of this operator, but it's one of them) -sub concat3($a, $b, $c) { -  say "$a, $b, $c"; -} -concat3(|@array); #=> a, b, c -                  # `@array` got "flattened" as a part of the argument list -  ## It can also have optional arguments:  sub with-optional($arg?) { # the "?" marks the argument optional -  say "I might return `(Any)` if I don't have an argument passed, -      or I'll return my argument"; +  say "I might return `(Any)` (Perl's "null"-like value) if I don't have +        an argument passed, or I'll return my argument";    $arg;  }  with-optional; # returns Any @@ -154,30 +119,27 @@ hello-to; #=> Hello, World !  hello-to(); #=> Hello, World !  hello-to('You'); #=> Hello, You ! -## You can also, by using a syntax akin to the one of hashes (yay unification !), +## You can also, by using a syntax akin to the one of hashes (yay unified syntax !),  ##  pass *named* arguments to a `sub`. +# They're optional, and will default to "Any".  sub with-named($normal-arg, :$named) {    say $normal-arg + $named;  }  with-named(1, named => 6); #=> 7  # There's one gotcha to be aware of, here:  # If you quote your key, Perl 6 won't be able to see it at compile time, -#  and you'll have a single Pair object as a positional paramater. +#  and you'll have a single Pair object as a positional parameter, +#  which means this fails: +with-named(1, 'named' => 6);  with-named(2, :named(5)); #=> 7 -with-named(3, :4named); #=> 7 -                        # (special colon pair syntax for numbers, -                        # to be used with s// and such, see later) - -with-named(3); # warns, because we tried to use the undefined $named in a `+`: -               # by default, named arguments are *optional*  # To make a named argument mandatory, you can use `?`'s inverse, `!`  sub with-mandatory-named(:$str!)  {    say "$str !";  }  with-mandatory-named(str => "My String"); #=> My String ! -with-mandatory-named; # run time error: "Required named parameter not passed"  +with-mandatory-named; # run time error: "Required named parameter not passed"  with-mandatory-named(3); # run time error: "Too many positional parameters passed"  ## If a sub takes a named boolean argument ... @@ -187,22 +149,37 @@ sub takes-a-bool($name, :$bool) {  # ... you can use the same "short boolean" hash syntax:  takes-a-bool('config', :bool); # config takes True  takes-a-bool('config', :!bool); # config takes False -# or you can use the "adverb" form: -takes-a-bool('config'):bool; #=> config takes True -takes-a-bool('config'):!bool; #=> config takes False -# You'll learn to love (or maybe hate, eh) that syntax later. -  ## You can also provide your named arguments with defaults:  sub named-def(:$def = 5) {    say $def;  }  named-def; #=> 5 -named-def(:10def); #=> 10  named-def(def => 15); #=> 15 -# -- Note: we're going to learn *more* on subs really soon, -#  but we need to grasp a few more things to understand their real power. Ready? +# Since you can omit parenthesis to call a function with no arguments, +#  you need "&" in the name to store `say-hello` in a variable. +my &s = &say-hello; +my &other-s = sub { say "Anonymous function !" } + +# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". +                             # Note: you can have parameters *before* (like here) +                             # a slurpy one, but not *after*. +  say @rest.join(' / ') ~ " !"; +} +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! +                                           # Note that the splat (the *) did not +                                           # consume the parameter before. + +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) +sub concat3($a, $b, $c) { +  say "$a, $b, $c"; +} +concat3(|@array); #=> a, b, c +                  # `@array` got "flattened" as a part of the argument list  ### Containers  # In Perl 6, values are actually stored in "containers". @@ -216,27 +193,23 @@ sub mutate($n is rw) {    say "\$n is now $n !";  } -# If what you want is a copy instead, use `is copy`. +# If what you want a copy instead, use `is copy`.  # A sub itself returns a container, which means it can be marked as rw:  my $x = 42; -sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory -            # (else Perl 6 thinks `mod` is a "term") +sub x-store() is rw { $x } +x-store() = 52; # in this case, the parentheses are mandatory +                # (else Perl 6 thinks `x-store` is an identifier)  say $x; #=> 52  ### Control Flow Structures - -# You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body: -  ## Conditionals  # - `if`  # Before talking about `if`, we need to know which values are "Truthy"  #  (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or `Int`),  #  and of course False itself.  # Every other value is Truthy.  if True { @@ -247,30 +220,40 @@ unless False {    say "It's not false !";  } +# As you can see, you don't need parentheses around conditions. +# However, you do need the brackets around the "body" block: +# if (true) say; # This doesn't work ! +  # You can also use their postfix versions, with the keyword after:  say "Quite truthy" if True; -# if (true) say; # This doesn't work ! -  # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)  my $a = $condition ?? $value-if-true !! $value-if-false; -# - `given`-`when` looks like other languages `switch`, but much more +# - `given`-`when` looks like other languages' `switch`, but much more  # powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. +#  # This variable contains the default argument of a block,  #  a loop's current iteration (unless explicitly named), etc. +#  # `given` simply puts its argument into `$_` (like a block would do),  #  and `when` compares it using the "smart matching" (`~~`) operator. +#  # Since other Perl 6 constructs use this variable (as said before, like `for`,  # blocks, etc), this means the powerful `when` is not only applicable along with  # a `given`, but instead anywhere a `$_` exists.  given "foo bar" { -  when /foo/ { # Don't worry about smart matching -- just know `when` uses it. +  say $_; #=> foo bar +  when /foo/ { # Don't worry about smart matching yet – just know `when` uses it.                 # This is equivalent to `if $_ ~~ /foo/`.      say "Yay !";    }    when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True,                         # so you can also put "normal" conditionals. +                       # This when is equivalent to this `if`: +                       #  if $_ ~~ ($_.chars > 50) {...} +                       # Which means: +                       #  if $_.chars > 50 {...}      say "Quite a long string !";    }    default { # same as `when *` (using the Whatever Star) @@ -281,7 +264,7 @@ given "foo bar" {  ## Looping constructs  # - `loop` is an infinite loop if you don't pass it arguments, -# but can also be a c-style `for`: +# but can also be a C-style `for` loop:  loop {    say "This is an infinite loop !";    last; # last breaks out of the loop, like the `break` keyword in other languages @@ -296,14 +279,14 @@ loop (my $i = 0; $i < 5; $i++) {  # - `for` - Passes through an array  for @array -> $variable { -  say "I've found $variable !"; +  say "I've got $variable !";  }  # As we saw with given, for's default "current iteration" variable is `$_`. -# That means you can use `when` in a `for` just like you were in a when. +# That means you can use `when` in a `for` just like you were in a `given`.  for @array {    say "I've got $_"; -   +    .say; # This is also allowed.          # A dot call with no "topic" (receiver) is sent to `$_` by default    $_.say; # the above and this are equivalent. @@ -316,45 +299,15 @@ for @array {    last if $_ == 5; # Or break out of a loop (like `break` in C-like languages).  } -# Note - the "lambda" `->` syntax isn't reserved to `for`: +# The "pointy block" syntax isn't specific to for. +# It's just a way to express a block in Perl6.  if long-computation() -> $result {    say "The result is $result";  } -## Loops can also have a label, and be jumped to through these. -OUTER: while 1 { -  say "hey"; -  while 1 { -    OUTER.last; # All the control keywords must be called on the label itself -  } -} - -# Now that you've seen how to traverse a list, you need to be aware of something: -# List context (@) flattens. If you traverse nested lists, you'll actually be traversing a -#  shallow list (except if some sub-list were put in item context ($)). -for 1, 2, (3, (4, ((5)))) { -  say "Got $_."; -} #=> Got 1. Got 2. Got 3. Got 4. Got 5. - -# ... However: (forcing item context with `$`) -for 1, 2, $(3, 4) { -  say "Got $_."; -} #=> Got 1. Got 2. Got 3 4. - -# Note that the last one actually joined 3 and 4. -# While `$(...)` will apply item to context to just about anything, you can also create -#  an array using `[]`: -for [1, 2, 3, 4] { -  say "Got $_."; -} #=> Got 1 2 3 4. - -# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array -#  whereas `$()` will return a Parcel when given a Parcel. - -  ### Operators -## Since Perl languages are very much operator-based languages +## Since Perl languages are very much operator-based languages,  ## Perl 6 operators are actually just funny-looking subroutines, in syntactic  ##  categories, like infix:<+> (addition) or prefix:<!> (bool not). @@ -394,9 +347,6 @@ $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg`  1 ~~ True; # smart-matching against a boolean always returns that boolean             # (and will warn). -# - `===` is value identity and uses `.WHICH` on the objects to compare them -# - `=:=` is container identity and uses `VAR()` on the objects to compare them -  # You also, of course, have `<`, `<=`, `>`, `>=`.  # Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`.  3 > 4; @@ -416,17 +366,25 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return                   # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !)  # Note : when reading an infinite list, Perl 6 will "reify" the elements  # it needs, then keep them in memory. They won't be calculated more than once. -                  -# Warning, though: if you try this example in the REPL and just put `1..*`, -#  Perl 6 will be forced to try and evaluate the whole array (to print it), -#  so you'll end with an infinite loop. +# It also will never calculate more elements that are needed. + +# An array subscript can also be a closure. +# It'll be called with the length as the argument +say join(' ', @array[15..*]); #=> 15 16 17 18 19 +# which is equivalent to: +say join(' ', @array[-> $n { 15..$n }]); +# Note: if you try to do either of those with an infinite loop, +#       you'll trigger an infinite loop (your program won't finish)  # You can use that in most places you'd expect, even assigning to an array  my @numbers = ^20; -@numbers[5..*] = 3, 9 ... * > 90; # The right hand side could be infinite as well. -                                  # (but not both, as this would be an infinite loop) -say @numbers; #=> 3 9 15 21 27 [...] 81 87 +# Here numbers increase by "6"; more on `...` operator later. +my @seq =  3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99; +@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, +                             # only the 15 needed values will be calculated. +say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87 +              # (only 20 values)  ## * And, Or  3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. @@ -438,7 +396,7 @@ $a && $b && $c; # Returns the first argument that evaluates to False,  $a || $b;  # And because you're going to want them, -#  you also have composed assignment operators: +#  you also have compound assignment operators:  $a *= 2; # multiply and assignment  $b %%= 5; # divisible by and assignment  @array .= sort; # calls the `sort` method and assigns the result back @@ -448,7 +406,7 @@ $b %%= 5; # divisible by and assignment  # a few more key concepts that make them better than in any other language :-).  ## Unpacking ! -# It's the ability to "extract" arrays and keys. +# It's the ability to "extract" arrays and keys (AKA "destructuring").  # It'll work in `my`s and in parameter lists.  my ($a, $b) = 1, 2;  say $a; #=> 1 @@ -559,6 +517,21 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)  # Note : those are sorted lexicographically.  # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +## About types... +# Perl6 is gradually typed. This means you can specify the type +#  of your variables/arguments/return types, or you can omit them +#  and they'll default to "Any". +# You obviously get access to a few base types, like Int and Str. +# The constructs for declaring types are "class", "role", +#  which you'll see later. + +# For now, let us examine "subset": +# a "subset" is a "sub-type" with additional checks. +# For example: "a very big integer is an Int that's greater than 500" +# You can specify the type you're subtyping (by default, Any), +#  and add additional checks with the "where" keyword: +subset VeryBigInteger of Int where * > 500; +  ## Multiple Dispatch  # Perl 6 can decide which variant of a `sub` to call based on the type of the  # arguments, or on arbitrary preconditions, like with a type or a `where`: @@ -567,20 +540,19 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)  multi sub sayit(Int $n) { # note the `multi` keyword here    say "Number: $n";  } -multi sayit(Str $s) } # the `sub` is the default +multi sayit(Str $s) { # a multi is a `sub` by default    say "String: $s";  }  sayit("foo"); # prints "String: foo"  sayit(True); # fails at *compile time* with               # "calling 'sayit' will never work with arguments of types ..." -# with arbitrary precondition: +# with arbitrary precondition (remember subsets?):  multi is-big(Int $n where * > 50) { "Yes !" } # using a closure  multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching                                                # (could use a regexp, etc)  multi is-big(Int $) { "No" } -# You can also name these checks, by creating "subsets":  subset Even of Int where * %% 2;  multi odd-or-even(Even) { "Even" } # The main case using the type. @@ -636,40 +608,39 @@ sub foo {    bar(); # call `bar` in-place  }  sub bar { -  say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, +  say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s,               #  even though the blocks aren't nested (they're call-nested).               #=> 1  }  ### Object Model -## Perl 6 has a quite comprehensive object model  # You declare a class with the keyword `class`, fields with `has`, -# methods with `method`. Every field to private, and is named `$!attr`, -# but you have `$.` to get a public (immutable) accessor along with it. -# (using `$.` is like using `$!` plus a `method` with the same name) +# methods with `method`. Every attribute that is private is named `$!attr`. +# Immutable public attributes are named `$.attr` +#   (you can make them mutable with `is rw`) -# (Perl 6's object model ("SixModel") is very flexible, +# Perl 6's object model ("SixModel") is very flexible,  # and allows you to dynamically add methods, change semantics, etc ...  # (this will not be covered here, and you should refer to the Synopsis).  class A {    has $.field; # `$.field` is immutable.                 # From inside the class, use `$!field` to modify it. -  has $.other-field is rw; # You can obviously mark a public field `rw`. +  has $.other-field is rw; # You can mark a public attribute `rw`.    has Int $!private-field = 10;    method get-value { -    $.field + $!private-field + $n; +    $.field + $!private-field;    } -   +    method set-value($n) {      # $.field = $n; # As stated before, you can't use the `$.` immutable version.      $!field = $n;   # This works, because `$!` is always mutable. -     +      $.other-field = 5; # This works, because `$.other-field` is `rw`.    } -   +    method !private-method {      say "This method is private to the class !";    } @@ -678,29 +649,28 @@ class A {  # Create a new instance of A with $.field set to 5 :  # Note: you can't set private-field from here (more later on).  my $a = A.new(field => 5); -$a.get-value; #=> 18 +$a.get-value; #=> 15  #$a.field = 5; # This fails, because the `has $.field` is immutable  $a.other-field = 10; # This, however, works, because the public field                       #  is mutable (`rw`).  ## Perl 6 also has inheritance (along with multiple inheritance) -# (though considered a misfeature by many)  class A {    has $.val; -   +    submethod not-inherited {      say "This method won't be available on B.";      say "This is most useful for BUILD, which we'll see later";    } -   +    method bar { $.val * 5 }  }  class B is A { # inheritance uses `is`    method foo {      say $.val;    } -   +    method bar { $.val * 10 } # this shadows A's `bar`  } @@ -724,23 +694,23 @@ role PrintableVal {    }  } -# you "use" a mixin with "does" : +# you "import" a mixin (a "role") with "does":  class Item does PrintableVal {    has $.val; -   +    # When `does`-ed, a `role` literally "mixes in" the class:    #  the methods and fields are put together, which means a class can access    #  the private fields/methods of its roles (but not the inverse !):    method access {      say $!counter++;    } -   +    # However, this:    # method print {}    # is ONLY valid when `print` isn't a `multi` with the same dispatch.    # (this means a parent class can shadow a child class's `multi print() {}`,    #  but it's an error if a role does) -   +    # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods    # will be shadowed, since the compiler will consider `ROLE` to be a class.  } @@ -779,7 +749,7 @@ fail "foo"; # We're not trying to access the value, so no problem.  try {    fail "foo";    CATCH { -    default { say "It threw because we try to get the fail's value!" } +    default { say "It threw because we tried to get the fail's value!" }    }  } @@ -791,25 +761,21 @@ try {  ### Packages  # Packages are a way to reuse code. Packages are like "namespaces", and any  #  element of the six model (`module`, `role`, `class`, `grammar`, `subset` -#  and `enum`) are actually packages. (Packages are the lowest common denomitor) +#  and `enum`) are actually packages. (Packages are the lowest common denominator)  # Packages are important - especially as Perl is well-known for CPAN,  #  the Comprehensive Perl Archive Network. -# You usually don't use packages directly: you use `class Package::Name::Here;`, -# or if you only want to export variables/subs, you can use `module`: +# You're not supposed to use the package keyword, usually: +#  you use `class Package::Name::Here;` to declare a class, +#  or if you only want to export variables/subs, you can use `module`:  module Hello::World { # Bracketed form                        # If `Hello` doesn't exist yet, it'll just be a "stub",                        #  that can be redeclared as something else later.    # ... declarations here ...  } -module Parse::Text; # file-scoped form +unit module Parse::Text; # file-scoped form  grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`  } -# NOTE for Perl 5 users: even though the `package` keyword exists, -#  the braceless form is invalid (to catch a "perl5ism"). This will error out: -# package Foo; # because Perl 6 will think the entire file is Perl 5 -# Just use `module` or the brace version of `package`. -  # You can use a module (bring its declarations into scope) with `use`  use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module  say from-json('[1]').perl; #=> [1] @@ -825,10 +791,8 @@ my $actions = JSON::Tiny::Actions.new;  # You've already seen `my` and `has`, we'll now explore the others.  ## * `our` (happens at `INIT` time -- see "Phasers" below) -# Along with `my`, there are several others declarators you can use. -# The first one you'll want for the previous part is `our`. +# It's like `my`, but it also creates a package variable.  # (All packagish things (`class`, `role`, etc) are `our` by default) -# it's like `my`, but it also creates a package variable:  module Foo::Bar {    our $n = 1; # note: you can't put a type constraint on an `our` variable    our sub inc { @@ -840,7 +804,7 @@ module Foo::Bar {        say "Can't access me from outside, I'm my !";      }    } -   +    say ++$n; # lexically-scoped variables are still available  }  say $Foo::Bar::n; #=> 1 @@ -857,7 +821,7 @@ constant why-not = 5, 15 ... *;  say why-not[^5]; #=> 5 15 25 35 45  ## * `state` (happens at run time, but only once) -# State variables are only executed one time +# State variables are only initialized one time  # (they exist in other langages such as C as `static`)  sub fixed-rand {    state $val = rand; @@ -890,7 +854,7 @@ for ^5 -> $a {  ## * Compile-time phasers  BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } -CHECK { say "[*] Runs at compile time, instead as late as possible, only once" } +CHECK { say "[*] Runs at compile time, as late as possible, only once" }  ## * Run-time phasers  INIT { say "[*] Runs at run time, as soon as possible, only once" } @@ -898,10 +862,21 @@ END { say "Runs at run time, as late as possible, only once" }  ## * Block phasers  ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } -LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." } +LEAVE { say "Runs everytime you leave a block, even when an exception +    happened. Repeats on loop blocks." } + +PRE { say "Asserts a precondition at every block entry, +    before ENTER (especially useful for loops)" } +# exemple: +for 0..2 { +    PRE { $_ > 1 } # This is going to blow up with "Precondition failed" +} -PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } -POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } +POST { say "Asserts a postcondition at every block exit, +    after LEAVE (especially useful for loops)" } +for 0..2 { +    POST { $_ < 2 } # This is going to blow up with "Postcondition failed" +}  ## * Block/exceptions phasers  sub { @@ -919,12 +894,12 @@ for ^5 {  ## * Role/class phasers  COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" } -# They allow for cute trick or clever code ...: -say "This code took " ~ (time - CHECK time) ~ "s to run"; +# They allow for cute tricks or clever code ...: +say "This code took " ~ (time - CHECK time) ~ "s to compile";  # ... or clever organization:  sub do-db-stuff { -  ENTER $db.start-transaction; # New transaction everytime we enter the sub +  $db.start-transaction; # start a new transaction    KEEP $db.commit; # commit the transaction if all went well    UNDO $db.rollback; # or rollback if all hell broke loose  } @@ -971,7 +946,7 @@ say join ',', gather if False {  # But consider:  constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything  # versus: -constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 3 4 +constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2  # - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)  # Not yet implemented !! @@ -1048,7 +1023,7 @@ sub circumfix:<[ ]>(Int $n) {    $n ** $n  }  say [5]; #=> 3125 -         # circumfix is around. Again, not whitespace. +         # circumfix is around. Again, no whitespace.  sub postcircumfix:<{ }>(Str $s, Int $idx) {    # post-circumfix is @@ -1072,7 +1047,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)  # *everything* -- with great power comes great responsibility)  ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep +# Oh boy, get ready. Get ready, because we're delving deep  #  into the rabbit's hole, and you probably won't want to go  #  back to other languages after reading that.  #  (I'm guessing you don't want to already at that point). @@ -1080,12 +1055,10 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)  # Basically, they're operators that apply another operator.  ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and +# It's a prefix meta-operator that takes a binary function and  #  one or many lists. If it doesn't get passed any argument, -#  it either return a "default value" for this operator -#  (a value that wouldn't change the result if passed as one -#   of the element of the list to be passed to the operator), -#  or `Any` if there's none (examples below). +#  it either returns a "default value" for this operator +#  (a meaningless value) or `Any` if there's none (examples below).  #  # Otherwise, it pops an element from the list(s) one at a time, and applies  #  the binary function to the last result (or the list's first element) @@ -1105,11 +1078,9 @@ say [//] Nil, Any, False, 1, 5; #=> False  # Default value examples: -say [*] (); #=> 1  -say [+] (); #=> 0  -            # In both cases, they're results that, were they in the lists, -            #  wouldn't have any impact on the final value -            #  (since N*1=N and N+0=N). +say [*] (); #=> 1 +say [+] (); #=> 0 +            # meaningless values, since N*1=N and N+0=N.  say [//];   #=> (Any)              # There's no "default value" for `//`. @@ -1121,7 +1092,7 @@ say [[&add]] 1, 2, 3; #=> 6  # This one is an infix meta-operator than also can be used as a "normal" operator.  # It takes an optional binary function (by default, it just creates a pair),  #  and will pop one value off of each array and call its binary function on these -#  until it runs out of elements. It runs the an array with all these new elements. +#  until it runs out of elements. It returns an array with all of these new elements.  (1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array  1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function @@ -1141,8 +1112,7 @@ say [[&add]] 1, 2, 3; #=> 6  #  (and might include a closure), and on the right, a value or the predicate  #  that says when to stop (or Whatever for a lazy infinite list).  my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, -                            #  because Perl 6 can't figure out the end +#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end  my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element                              # (the iteration when the predicate matches).  my @list = 1, 3, 9 ... * > 30; # you can use a predicate @@ -1163,90 +1133,6 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55  # That's why `@primes[^100]` will take a long time the first time you print  #  it, then be instant. - -## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` -#  (which numerify to -1, 0 or +1). -1 <=> 4; # sort comparison for numerics -'a' leg 'b'; # sort comparison for string -$obj eqv $obj2; # sort comparison using eqv semantics - -## * Generic ordering -3 before 4; # True -'b' after 'a'; # True - -## * Short-circuit default operator -# Like `or` and `||`, but instead returns the first *defined* value : -say Any // Nil // 0 // 5; #=> 0 - -## * Short-circuit exclusive or (XOR) -# Returns `True` if one (and only one) of its arguments is true -say True ^^ False; #=> True - -## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). -#  are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until -#  their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` -#  by using `^` on either side. -# Let's start with an example : -for <well met young hero we shall meet later> { -  # by default, `ff`/`fff` smart-match (`~~`) against `$_`: -  if 'met' ^ff 'meet' { # Won't enter the if for "met" -                        #  (explained in details below). -    .say -  } -   -  if rand == 0 ff rand == 1 { # compare variables other than `$_` -    say "This ... probably will never run ..."; -  } -} -# This will print "young hero we shall meet" (excluding "met"): -#  the flip-flop will start returning `True` when it first encounters "met" -#  (but will still return `False` for "met" itself, due to the leading `^` -#   on `ff`), until it sees "meet", which is when it'll start returning `False`. - -# The difference between `ff` (awk-style) and `fff` (sed-style) is that -#  `ff` will test its right side right when its left side changes to `True`, -#  and can get back to `False` right away -#  (*except* it'll be `True` for the iteration that matched) - -# While `fff` will wait for the next iteration to -#  try its right side, once its left side changed: -.say if 'B' ff 'B' for <A B C B A>; #=> B B -                                    # because the right-hand-side was tested -                                    # directly (and returned `True`). -                                    # "B"s are printed since it matched that time -                                    #  (it just went back to `False` right away). -.say if 'B' fff 'B' for <A B C B A>; #=> B C B -                                    # The right-hand-side wasn't tested until -                                    #  `$_` became "C" -                                    # (and thus did not match instantly). - -# A flip-flop can change state as many times as needed: -for <test start print it stop not printing start print again stop not anymore> { -  .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", -                                           #=> "print this printing again" -} - -# you might also use a Whatever Star, -# which is equivalent to `True` for the left side or `False` for the right: -for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here -                            # (sometimes called "superstitious parentheses") - .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, -                       #  it'll never go back to `False` -                       #=> 60 3 40 60 -} - -# You can also use this property to create an `If` -#  that'll not go through the first time : -for <a b c> { -  .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, -                   #  but the `^` makes it *not run* on the first iteration -                   #=> b c -} - -  ### Regular Expressions  # I'm sure a lot of you have been waiting for this one.  # Well, now that you know a good deal of Perl 6 already, we can get started. @@ -1338,7 +1224,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)  #  they use a more perl6-ish syntax:  say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'  # You can use ranges: -say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou' +say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae'  # Just like in normal regexes, if you want to use a special character, escape it  #  (the last one is escaping a space)  say 'he-he !' ~~ / 'he-' <[ a..z \! \  ]> + /; #=> 'he-he !' @@ -1358,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left  # Group: you can group parts of your regexp with `[]`.  # These groups are *not* captured (like PCRE's `(?:)`).  so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing -so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; +so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;  # The previous line returns `True`. -# We match the "abc" 1 or more time (the `+` was applied to the group). +# We match the "012" 1 or more time (the `+` was applied to the group).  # But this does not go far enough, because we can't actually get back what  #  we matched.  # Capture: We can actually *capture* the results of the regexp, using parentheses. -so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below) +so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)  # So, starting with the grouping explanations.  # As we said before, our `Match` object is available as `$/`: @@ -1403,10 +1289,12 @@ say $/[0][0].Str; #=> ~  # This stems from a very simple fact: `$/` does not contain strings, integers or arrays,  #  it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods. -#  (but you can also just use `match<key>` for hash access and `match[idx]` for array access) +#  (but you can also just use `match<key>` for hash access +#    and `match[idx]` for array access)  say $/[0].list.perl; #=> (Match.new(...),).list -                     # We can see it's a list of Match objects. Those contain a bunch of infos: -                     # where the match started/ended, the "ast" (see actions later), etc. +                     # We can see it's a list of Match objects. Those contain +                     # a bunch of infos: where the match started/ended, +                     #    the "ast" (see actions later), etc.                       # You'll see named capture below with grammars.  ## Alternatives - the `or` of regexps @@ -1444,14 +1332,14 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...  ### Extra: the MAIN subroutime  # The `MAIN` subroutine is called when you run a Perl 6 file directly. -# It's very powerful, because Perl 6 actually parses the argument +# It's very powerful, because Perl 6 actually parses the arguments  #  and pass them as such to the sub. It also handles named argument (`--foo`)  #  and will even go as far as to autogenerate a `--help`  sub MAIN($name) { say "Hello, $name !" }  # This produces:  #    $ perl6 cli.pl  #    Usage: -#      t.pl <name>  +#      t.pl <name>  # And since it's a regular Perl 6 sub, you can haz multi-dispatch:  # (using a "Bool" for the named argument so that we can do `--replace` @@ -1462,14 +1350,113 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }  multi MAIN('remove', $key) { ... }  multi MAIN('import', File, Str :$as) { ... } # omitting parameter name  # This produces: -#    $ perl 6 cli.pl +#    $ perl6 cli.pl  #    Usage: -#      t.pl [--replace] add <key> <value>  +#      t.pl [--replace] add <key> <value>  #      t.pl remove <key>  #      t.pl [--as=<Str>] import (File)  # As you can see, this is *very* powerful.  # It even went as far as to show inline the constants.  # (the type is only displayed if the argument is `$`/is named) + +### +### APPENDIX A: +### +### List of things +### + +# It's considered by now you know the Perl6 basics. +# This section is just here to list some common operations, +#  but which are not in the "main part" of the tutorial to bloat it up + +## Operators + + +## * Sort comparison +# They return one value of the `Order` enum : `Less`, `Same` and `More` +#  (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + +## * Short-circuit default operator +# Like `or` and `||`, but instead returns the first *defined* value : +say Any // Nil // 0 // 5; #=> 0 + +## * Short-circuit exclusive or (XOR) +# Returns `True` if one (and only one) of its arguments is true +say True ^^ False; #=> True +## * Flip Flop +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). +#  are operators that take two predicates to test: +# They are `False` until their left side returns `True`, then are `True` until +#  their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +#  by using `^` on either side. +# Let's start with an example : +for <well met young hero we shall meet later> { +  # by default, `ff`/`fff` smart-match (`~~`) against `$_`: +  if 'met' ^ff 'meet' { # Won't enter the if for "met" +                        #  (explained in details below). +    .say +  } + +  if rand == 0 ff rand == 1 { # compare variables other than `$_` +    say "This ... probably will never run ..."; +  } +} +# This will print "young hero we shall meet" (excluding "met"): +#  the flip-flop will start returning `True` when it first encounters "met" +#  (but will still return `False` for "met" itself, due to the leading `^` +#   on `ff`), until it sees "meet", which is when it'll start returning `False`. + +# The difference between `ff` (awk-style) and `fff` (sed-style) is that +#  `ff` will test its right side right when its left side changes to `True`, +#  and can get back to `False` right away +#  (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +#  try its right side, once its left side changed: +.say if 'B' ff 'B' for <A B C B A>; #=> B B +                                    # because the right-hand-side was tested +                                    # directly (and returned `True`). +                                    # "B"s are printed since it matched that time +                                    #  (it just went back to `False` right away). +.say if 'B' fff 'B' for <A B C B A>; #=> B C B +                                    # The right-hand-side wasn't tested until +                                    #  `$_` became "C" +                                    # (and thus did not match instantly). + +# A flip-flop can change state as many times as needed: +for <test start print it stop not printing start print again stop not anymore> { +  .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", +                                           #=> "print it print again" +} + +# you might also use a Whatever Star, +# which is equivalent to `True` for the left side or `False` for the right: +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here +                            # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, +                       #  it'll never go back to `False` +                       #=> 60 3 40 60 +} + +# You can also use this property to create an `If` +#  that'll not go through the first time : +for <a b c> { +  .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, +                   #  but the `^` makes it *not run* on the first iteration +                   #=> b c +} + + +# - `===` is value identity and uses `.WHICH` on the objects to compare them +# - `=:=` is container identity and uses `VAR()` on the objects to compare them +  ```  If you want to go further, you can: @@ -1477,5 +1464,4 @@ If you want to go further, you can:   - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such.   - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.   - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. - + - Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting. | 
