Raku

Личный сайт Go-разработчика из Казани

Raku (formerly Perl 6) is a highly capable, feature-rich programming language made for at least the next hundred years.

The primary Raku compiler is called Rakudo, which runs on the JVM and the MoarVM.

Meta-note:

  • Although the pound sign (#) is used for sentences and notes, Pod-styled comments (more below about them) are used whenever it’s convenient.
  • # OUTPUT: is used to represent the output of a command to any standard stream. If the output has a newline, it’s represented by the symbol. The output is always enclosed by angle brackets (« and »).
  • #=> represents the value of an expression, return value of a sub, etc. In some cases, the value is accompanied by a comment.
  • Backticks are used to distinguish and highlight the language constructs from the text.
1#################################################### 2# 0. Comments 3#################################################### 4 5# Single line comments start with a pound sign. 6 7#`( Multiline comments use #` and a quoting construct. 8 (), [], {}, 「」, etc, will work. 9) 10 11=for comment 12Use the same syntax for multiline comments to embed comments. 13for #`(each element in) @array { 14 put #`(or print element) $_ #`(with newline); 15} 16 17# You can also use Pod-styled comments. For example: 18 19=comment This is a comment that extends until an empty 20newline is found. 21 22=comment 23The comment doesn't need to start in the same line as the directive. 24 25=begin comment 26This comment is multiline. 27 28Empty newlines can exist here too! 29=end comment 30 31#################################################### 32# 1. Variables 33#################################################### 34 35# In Raku, you declare a lexical variable using the `my` keyword: 36my $variable; 37 38# Raku has 3 basic types of variables: scalars, arrays, and hashes. 39 40# 41# 1.1 Scalars 42# 43 44# Scalars represent a single value. They start with the `$` sigil: 45my $str = 'String'; 46 47# Double quotes allow for interpolation (which we'll see later): 48my $str2 = "$str"; 49 50# Variable names can contain but not end with simple quotes and dashes, 51# and can contain (and end with) underscores: 52my $person's-belongings = 'towel'; # this works! 53 54my $bool = True; # `True` and `False` are Raku's boolean values. 55my $inverse = !$bool; # Invert a bool with the prefix `!` operator. 56my $forced-bool = so $str; # And you can use the prefix `so` operator 57$forced-bool = ?$str; # to turn its operand into a Bool. Or use `?`. 58 59# 60# 1.2 Arrays and Lists 61# 62 63# Arrays represent multiple values. An array variable starts with the `@` 64# sigil. Unlike lists, from which arrays inherit, arrays are mutable. 65 66my @array = 'a', 'b', 'c'; 67# equivalent to: 68my @letters = <a b c>; 69# In the previous statement, we use the quote-words (`<>`) term for array 70# of words, delimited by space. Similar to perl's qw, or Ruby's %w. 71 72@array = 1, 2, 4; 73 74# Array indices start at 0. Here the third element is being accessed. 75say @array[2]; # OUTPUT: «4␤» 76 77say "Interpolate an array using []: @array[]"; 78# OUTPUT: «Interpolate an array using []: 1 2 3␤» 79 80@array[0] = -1; # Assigning a new value to an array index 81@array[0, 1] = 5, 6; # Assigning multiple values 82 83my @keys = 0, 2; 84@array[@keys] = @letters; # Assignment using an array containing index values 85say @array; # OUTPUT: «a 6 b␤» 86 87# 88# 1.3 Hashes, or key-value Pairs. 89# 90 91# Hashes are pairs of keys and values. You can construct a `Pair` object 92# using the syntax `key => value`. Hash tables are very fast for lookup, 93# and are stored unordered. Keep in mind that keys get "flattened" in hash 94# context, and any duplicated keys are deduplicated. 95my %hash = 'a' => 1, 'b' => 2; 96 97# Keys get auto-quoted when the fat comma (`=>`) is used. Trailing commas are 98# okay. 99%hash = a => 1, b => 2, ; 100 101# Even though hashes are internally stored differently than arrays, 102# Raku allows you to easily create a hash from an even numbered array: 103%hash = <key1 value1 key2 value2>; # Or: 104%hash = "key1", "value1", "key2", "value2"; 105 106%hash = key1 => 'value1', key2 => 'value2'; # same result as above 107 108# You can also use the "colon pair" syntax. This syntax is especially 109# handy for named parameters that you'll see later. 110%hash = :n(2), # equivalent to `n => 2` 111 :is-even, # equivalent to `:is-even(True)` or `is-even => True` 112 :!is-odd, # equivalent to `:is-odd(False)` or `is-odd => False` 113; 114# The `:` (as in `:is-even`) and `:!` (as `:!is-odd`) constructs are known 115# as the `True` and `False` shortcuts respectively. 116 117# As demonstrated in the example below, you can use {} to get the value from a key. 118# If it's a string without spaces, you can actually use the quote-words operator 119# (`<>`). Since Raku doesn't have barewords, as Perl does, `{key1}` doesn't work 120# though. 121say %hash{'n'}; # OUTPUT: «2␤», gets value associated to key 'n' 122say %hash<is-even>; # OUTPUT: «True␤», gets value associated to key 'is-even' 123 124#################################################### 125# 2. Subroutines 126#################################################### 127 128# Subroutines, or functions as most other languages call them, are 129# created with the `sub` keyword. 130sub say-hello { say "Hello, world" } 131 132# You can provide (typed) arguments. If specified, the type will be checked 133# at compile-time if possible, otherwise at runtime. 134sub say-hello-to( Str $name ) { 135 say "Hello, $name !"; 136} 137 138# A sub returns the last value of the block. Similarly, the semicolon in 139# the last expression can be omitted. 140sub return-value { 5 } 141say return-value; # OUTPUT: «5␤» 142 143sub return-empty { } 144say return-empty; # OUTPUT: «Nil␤» 145 146# Some control flow structures produce a value, for instance `if`: 147sub return-if { 148 if True { "Truthy" } 149} 150say return-if; # OUTPUT: «Truthy␤» 151 152# Some don't, like `for`: 153sub return-for { 154 for 1, 2, 3 { 'Hi' } 155} 156say return-for; # OUTPUT: «Nil␤» 157 158# Positional arguments are required by default. To make them optional, use 159# the `?` after the parameters' names. 160 161# In the following example, the sub `with-optional` returns `(Any)` (Perl's 162# null-like value) if no argument is passed. Otherwise, it returns its argument. 163sub with-optional( $arg? ) { 164 $arg; 165} 166with-optional; # returns Any 167with-optional(); # returns Any 168with-optional(1); # returns 1 169 170# You can also give provide a default value when they're not passed. Doing 171# this make said parameter optional. Required parameters must come before 172# optional ones. 173 174# In the sub `greeting`, the parameter `$type` is optional. 175sub greeting( $name, $type = "Hello" ) { 176 say "$type, $name!"; 177} 178 179greeting("Althea"); # OUTPUT: «Hello, Althea!␤» 180greeting("Arthur", "Good morning"); # OUTPUT: «Good morning, Arthur!␤» 181 182# You can also, by using a syntax akin to the one of hashes (yay unified syntax!), 183# declared named parameters and thus pass named arguments to a subroutine. 184# By default, named parameter are optional and will default to `Any`. 185sub with-named( $normal-arg, :$named ) { 186 say $normal-arg + $named; 187} 188with-named(1, named => 6); # OUTPUT: «7␤» 189 190# There's one gotcha to be aware of, here: If you quote your key, Raku 191# won't be able to see it at compile time, and you'll have a single `Pair` 192# object as a positional parameter, which means the function subroutine 193# `with-named(1, 'named' => 6);` fails. 194with-named(2, :named(5)); # OUTPUT: «7␤» 195 196# Similar to positional parameters, you can provide your named arguments with 197# default values. 198sub named-def( :$def = 5 ) { 199 say $def; 200} 201named-def; # OUTPUT: «5» 202named-def(def => 15); # OUTPUT: «15» 203 204# In order to make a named parameter mandatory, you can append `!` to the 205# parameter. This is the inverse of `?`, which makes a required parameter 206# optional. 207 208sub with-mandatory-named( :$str! ) { 209 say "$str!"; 210} 211with-mandatory-named(str => "My String"); # OUTPUT: «My String!␤» 212# with-mandatory-named; # runtime error: "Required named parameter not passed" 213# with-mandatory-named(3);# runtime error: "Too many positional parameters passed" 214 215# If a sub takes a named boolean argument, you can use the same "short boolean" 216# hash syntax we discussed earlier. 217sub takes-a-bool( $name, :$bool ) { 218 say "$name takes $bool"; 219} 220takes-a-bool('config', :bool); # OUTPUT: «config takes True␤» 221takes-a-bool('config', :!bool); # OUTPUT: «config takes False␤» 222 223# Since parenthesis can be omitted when calling a subroutine, you need to use 224# `&` in order to distinguish between a call to a sub with no arguments and 225# the code object. 226 227# For instance, in this example we must use `&` to store the sub `say-hello` 228# (i.e., the sub's code object) in a variable, not a subroutine call. 229my &s = &say-hello; 230my &other-s = sub { say "Anonymous function!" } 231 232# A sub can have a "slurpy" parameter, or what one'd call a 233# "doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic 234# functions. For this, you must use `*@` (slurpy) which will "take everything 235# else". You can have as many parameters *before* a slurpy one, but not *after*. 236sub as-many($head, *@rest) { 237 @rest.join(' / ') ~ " !"; 238} 239say as-many('Happy', 'Happy', 'Birthday'); # OUTPUT: «Happy / Birthday !␤» 240say as-many('Happy', ['Happy', 'Birthday'], 'Day'); # OUTPUT: «Happy / Birthday / Day !␤» 241 242# Note that the splat (the *) did not consume the parameter before it. 243 244# There are other two variations of slurpy parameters in Raku. The previous one 245# (namely, `*@`), known as flattened slurpy, flattens passed arguments. The other 246# two are `**@` and `+@` known as unflattened slurpy and "single argument rule" 247# slurpy respectively. The unflattened slurpy doesn't flatten its listy 248# arguments (or Iterable ones). 249sub b(**@arr) { @arr.perl.say }; 250b(['a', 'b', 'c']); # OUTPUT: «[["a", "b", "c"],]» 251b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]» 252b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» 253 254# On the other hand, the "single argument rule" slurpy follows the "single argument 255# rule" which dictates how to handle the slurpy argument based upon context and 256# roughly states that if only a single argument is passed and that argument is 257# Iterable, that argument is used to fill the slurpy parameter array. In any 258# other case, `+@` works like `**@`. 259sub c(+@arr) { @arr.perl.say }; 260c(['a', 'b', 'c']); # OUTPUT: «["a", "b", "c"]␤» 261c(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤» 262c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» 263 264# You can call a function with an array using the "argument list flattening" 265# operator `|` (it's not actually the only role of this operator, 266# but it's one of them). 267sub concat3($a, $b, $c) { 268 say "$a, $b, $c"; 269} 270concat3(|@array); # OUTPUT: «a, b, c␤» 271 # `@array` got "flattened" as a part of the argument list 272 273#################################################### 274# 3. Containers 275#################################################### 276 277# In Raku, values are actually stored in "containers". The assignment 278# operator asks the container on the left to store the value on its right. 279# When passed around, containers are marked as immutable which means that, 280# in a function, you'll get an error if you try to mutate one of your 281# arguments. If you really need to, you can ask for a mutable container by 282# using the `is rw` trait. 283sub mutate( $n is rw ) { 284 $n++; # postfix ++ operator increments its argument but returns its old value 285} 286my $m = 42; 287mutate $m; #=> 42, the value is incremented but the old value is returned 288say $m; # OUTPUT: «43␤» 289 290# This works because we are passing the container $m to the `mutate` sub. 291# If we try to just pass a number instead of passing a variable, it won't work 292# because there is no container being passed and integers are immutable by 293# themselves: 294 295# mutate 42; # Parameter '$n' expected a writable container, but got Int value 296 297# Similar error would be obtained, if a bound variable is passed to 298# to the subroutine. In Raku, you bind a value to a variable using the binding 299# operator `:=`. 300my $v := 50; # binding 50 to the variable $v 301# mutate $v; # Parameter '$n' expected a writable container, but got Int value 302 303# If what you want is a copy instead, use the `is copy` trait which will 304# cause the argument to be copied and allow you to modify the argument 305# inside the routine without modifying the passed argument. 306 307# A sub itself returns a container, which means it can be marked as `rw`. 308# Alternatively, you can explicitly mark the returned container as mutable 309# by using `return-rw` instead of `return`. 310my $x = 42; 311my $y = 45; 312sub x-store is rw { $x } 313sub y-store { return-rw $y } 314 315# In this case, the parentheses are mandatory or else Raku thinks that 316# `x-store` and `y-store` are identifiers. 317x-store() = 52; 318y-store() *= 2; 319 320say $x; # OUTPUT: «52␤» 321say $y; # OUTPUT: «90␤» 322 323#################################################### 324# 4.Control Flow Structures 325#################################################### 326 327# 328# 4.1 if/if-else/if-elsif-else/unless 329# 330 331# Before talking about `if`, we need to know which values are "truthy" 332# (represent `True`), and which are "falsey" (represent `False`). Only these 333# values are falsey: 0, (), {}, "", Nil, a type (like `Str`, `Int`, etc.) and 334# of course, `False` itself. Any other value is truthy. 335my $number = 5; 336if $number < 5 { 337 say "Number is less than 5" 338} 339elsif $number == 5 { 340 say "Number is equal to 5" 341} 342else { 343 say "Number is greater than 5" 344} 345 346unless False { 347 say "It's not false!"; 348} 349 350# `unless` is the equivalent of `if not (X)` which inverts the sense of a 351# conditional statement. However, you cannot use `else` or `elsif` with it. 352 353# As you can see, you don't need parentheses around conditions. However, you 354# do need the curly braces around the "body" block. For example, 355# `if (True) say 'It's true';` doesn't work. 356 357# You can also use their statement modifier (postfix) versions: 358say "Quite truthy" if True; # OUTPUT: «Quite truthy␤» 359say "Quite falsey" unless False; # OUTPUT: «Quite falsey␤» 360 361# The ternary operator (`??..!!`) is structured as follows `condition ?? 362# expression1 !! expression2` and it returns expression1 if the condition is 363# true. Otherwise, it returns expression2. 364my $age = 30; 365say $age > 18 ?? "You are an adult" !! "You are under 18"; 366# OUTPUT: «You are an adult␤» 367 368# 369# 4.2 with/with-else/with-orwith-else/without 370# 371 372# The `with` statement is like `if`, but it tests for definedness rather than 373# truth, and it topicalizes on the condition, much like `given` which will 374# be discussed later. 375my $s = "raku"; 376with $s.index("r") { say "Found a at $_" } 377orwith $s.index("k") { say "Found c at $_" } 378else { say "Didn't find r or k" } 379 380# Similar to `unless` that checks un-truthiness, you can use `without` to 381# check for undefined-ness. 382my $input01; 383without $input01 { 384 say "No input given." 385} 386# OUTPUT: «No input given.␤» 387 388# There are also statement modifier versions for both `with` and `without`. 389my $input02 = 'Hello'; 390say $input02 with $input02; # OUTPUT: «Hello␤» 391say "No input given." without $input02; 392 393# 394# 4.3 given/when, or Raku's switch construct 395# 396 397=begin comment 398`given...when` looks like other languages' `switch`, but is much more 399powerful thanks to smart matching and Raku's "topic variable", `$_`. 400 401The topic variable `$_ `contains the default argument of a block, a loop's 402current iteration (unless explicitly named), etc. 403 404`given` simply puts its argument into `$_` (like a block would do), 405 and `when` compares it using the "smart matching" (`~~`) operator. 406 407Since other Raku constructs use this variable (as said before, like `for`, 408blocks, `with` statement etc), this means the powerful `when` is not only 409applicable along with a `given`, but instead anywhere a `$_` exists. 410 411=end comment 412 413given "foo bar" { 414 say $_; # OUTPUT: «foo bar␤» 415 416 # Don't worry about smart matching yet. Just know `when` uses it. This is 417 # equivalent to `if $_ ~~ /foo/`. 418 when /foo/ { 419 say "Yay !"; 420 } 421 422 # smart matching anything with `True` is `True`, i.e. (`$a ~~ True`) 423 # so you can also put "normal" conditionals. For example, this `when` is 424 # equivalent to this `if`: `if $_ ~~ ($_.chars > 50) {...}` 425 # which means: `if $_.chars > 50 {...}` 426 when $_.chars > 50 { 427 say "Quite a long string !"; 428 } 429 430 # same as `when *` (using the Whatever Star) 431 default { 432 say "Something else" 433 } 434} 435 436# 437# 4.4 Looping constructs 438# 439 440# The `loop` construct is an infinite loop if you don't pass it arguments, but 441# can also be a C-style `for` loop: 442loop { 443 say "This is an infinite loop !"; 444 last; 445} 446# In the previous example, `last` breaks out of the loop very much 447# like the `break` keyword in other languages. 448 449# The `next` keyword skips to the next iteration, like `continue` in other 450# languages. Note that you can also use postfix conditionals, loops, etc. 451loop (my $i = 0; $i < 5; $i++) { 452 next if $i == 3; 453 say "This is a C-style for loop!"; 454} 455 456# The `for` constructs iterates over a list of elements. 457my @odd-array = 1, 3, 5, 7, 9; 458 459# Accessing the array's elements with the topic variable $_. 460for @odd-array { 461 say "I've got $_ !"; 462} 463 464# Accessing the array's elements with a "pointy block", `->`. 465# Here each element is read-only. 466for @odd-array -> $variable { 467 say "I've got $variable !"; 468} 469 470# Accessing the array's elements with a "doubly pointy block", `<->`. 471# Here each element is read-write so mutating `$variable` mutates 472# that element in the array. 473for @odd-array <-> $variable { 474 say "I've got $variable !"; 475} 476 477# As we saw with `given`, a `for` loop's default "current iteration" variable 478# is `$_`. That means you can use `when` in a `for`loop just like you were 479# able to in a `given`. 480for @odd-array { 481 say "I've got $_"; 482 483 # This is also allowed. A dot call with no "topic" (receiver) is sent to 484 # `$_` (topic variable) by default. 485 .say; 486 487 # This is equivalent to the above statement. 488 $_.say; 489} 490 491for @odd-array { 492 # You can... 493 next if $_ == 3; # Skip to the next iteration (`continue` in C-like lang.) 494 redo if $_ == 4; # Re-do iteration, keeping the same topic variable (`$_`) 495 last if $_ == 5; # Or break out of loop (like `break` in C-like lang.) 496} 497 498# The "pointy block" syntax isn't specific to the `for` loop. It's just a way 499# to express a block in Raku. 500sub long-computation { "Finding factors of large primes" } 501if long-computation() -> $result { 502 say "The result is $result."; 503} 504 505#################################################### 506# 5. Operators 507#################################################### 508 509=begin comment 510Since Perl languages are very much operator-based languages, Raku 511operators are actually just funny-looking subroutines, in syntactic 512categories, like infix:<+> (addition) or prefix:<!> (bool not). 513 514The categories are: 515 - "prefix": before (like `!` in `!True`). 516 - "postfix": after (like `++` in `$a++`). 517 - "infix": in between (like `*` in `4 * 3`). 518 - "circumfix": around (like `[`-`]` in `[1, 2]`). 519 - "post-circumfix": around, after another term (like `{`-`}` in 520 `%hash{'key'}`) 521 522The associativity and precedence list are explained below. 523 524Alright, you're set to go! 525 526=end comment 527 528# 529# 5.1 Equality Checking 530# 531 532# `==` is numeric comparison 533say 3 == 4; # OUTPUT: «False␤» 534say 3 != 4; # OUTPUT: «True␤» 535 536# `eq` is string comparison 537say 'a' eq 'b'; # OUTPUT: «False␤» 538say 'a' ne 'b'; # OUTPUT: «True␤», not equal 539say 'a' !eq 'b'; # OUTPUT: «True␤», same as above 540 541# `eqv` is canonical equivalence (or "deep equality") 542say (1, 2) eqv (1, 3); # OUTPUT: «False␤» 543say (1, 2) eqv (1, 2); # OUTPUT: «True␤» 544say Int === Int; # OUTPUT: «True␤» 545 546# `~~` is the smart match operator which aliases the left hand side to $_ and 547# then evaluates the right hand side. 548# Here are some common comparison semantics: 549 550# String or numeric equality 551say 'Foo' ~~ 'Foo'; # OUTPUT: «True␤», if strings are equal. 552say 12.5 ~~ 12.50; # OUTPUT: «True␤», if numbers are equal. 553 554# Regex - For matching a regular expression against the left side. 555# Returns a `Match` object, which evaluates as True if regexp matches. 556my $obj = 'abc' ~~ /a/; 557say $obj; # OUTPUT: «「a」␤» 558say $obj.WHAT; # OUTPUT: «(Match)␤» 559 560# Hashes 561say 'key' ~~ %hash; # OUTPUT: «True␤», if key exists in hash. 562 563# Type - Checks if left side "is of type" (can check superclasses and roles). 564say 1 ~~ Int; # OUTPUT: «True␤» 565 566# Smart-matching against a boolean always returns that boolean (and will warn). 567say 1 ~~ True; # OUTPUT: «True␤», smartmatch against True always matches 568say False.so ~~ True; # OUTPUT: «True␤», use .so for truthiness 569 570# General syntax is `$arg ~~ &bool-returning-function;`. For a complete list 571# of combinations, refer to the table at: 572# https://docs.raku.org/language/operators#index-entry-smartmatch_operator 573 574# Of course, you also use `<`, `<=`, `>`, `>=` for numeric comparison. 575# Their string equivalent are also available: `lt`, `le`, `gt`, `ge`. 576say 3 > 4; # OUTPUT: «False␤» 577say 3 >= 4; # OUTPUT: «False␤» 578say 3 < 4; # OUTPUT: «True␤» 579say 3 <= 4; # OUTPUT: «True␤» 580say 'a' gt 'b'; # OUTPUT: «False␤» 581say 'a' ge 'b'; # OUTPUT: «False␤» 582say 'a' lt 'b'; # OUTPUT: «True␤» 583say 'a' le 'b'; # OUTPUT: «True␤» 584 585# 586# 5.2 Range constructor 587# 588 589say 3 .. 7; # OUTPUT: «3..7␤», both included. 590say 3 ..^ 7; # OUTPUT: «3..^7␤», exclude right endpoint. 591say 3 ^.. 7; # OUTPUT: «3^..7␤», exclude left endpoint. 592say 3 ^..^ 7; # OUTPUT: «3^..^7␤», exclude both endpoints. 593 594# The range 3 ^.. 7 is similar like 4 .. 7 when we only consider integers. 595# But when we consider decimals: 596 597say 3.5 ~~ 4 .. 7; # OUTPUT: «False␤» 598say 3.5 ~~ 3 ^.. 7; # OUTPUT: «True␤», 599 600# This is because the range `3 ^.. 7` only excludes anything strictly 601# equal to 3. Hence, it contains decimals greater than 3. This could 602# mathematically be described as 3.5 ∈ (3,7] or in set notation, 603# 3.5 ∈ { x | 3 < x ≤ 7 }. 604 605say 3 ^.. 7 ~~ 4 .. 7; # OUTPUT: «False␤» 606 607# This also works as a shortcut for `0..^N`: 608say ^10; # OUTPUT: «^10␤», which means 0..^10 609 610# This also allows us to demonstrate that Raku has lazy/infinite arrays, 611# using the Whatever Star: 612my @natural = 1..*; # 1 to Infinite! Equivalent to `1..Inf`. 613 614# You can pass ranges as subscripts and it'll return an array of results. 615say @natural[^10]; # OUTPUT: «1 2 3 4 5 6 7 8 9 10␤», doesn't run out of memory! 616 617# NOTE: when reading an infinite list, Raku will "reify" the elements 618# it needs, then keep them in memory. They won't be calculated more than once. 619# It also will never calculate more elements than that are needed. 620 621# An array subscript can also be a closure. It'll be called with the array's 622# length as the argument. The following two examples are equivalent: 623say join(' ', @array[15..*]); # OUTPUT: «15 16 17 18 19␤» 624say join(' ', @array[-> $n { 15..$n }]); # OUTPUT: «15 16 17 18 19␤» 625 626# NOTE: if you try to do either of those with an infinite array, you'll 627# trigger an infinite loop (your program won't finish). 628 629# You can use that in most places you'd expect, even when assigning to an array: 630my @numbers = ^20; 631 632# Here the numbers increase by 6, like an arithmetic sequence; more on the 633# sequence (`...`) operator later. 634my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99; 635 636# In this example, even though the sequence is infinite, only the 15 637# needed values will be calculated. 638@numbers[5..*] = 3, 9 ... *; 639say @numbers; # OUTPUT: «0 1 2 3 4 3 9 15 21 [...] 81 87␤», only 20 values 640 641# 642# 5.3 and (&&), or (||) 643# 644 645# Here `and` calls `.Bool` on both 3 and 4 and gets `True` so it returns 646# 4 since both are `True`. 647say (3 and 4); # OUTPUT: «4␤», which is truthy. 648say (3 and 0); # OUTPUT: «0␤» 649say (0 and 4); # OUTPUT: «0␤» 650 651# Here `or` calls `.Bool` on `0` and `False` which are both `False` 652# so it returns `False` since both are `False`. 653say (0 or False); # OUTPUT: «False␤». 654 655# Both `and` and `or` have tighter versions which also shortcut circuits. 656# They're `&&` and `||` respectively. 657 658# `&&` returns the first operand that evaluates to `False`. Otherwise, 659# it returns the last operand. 660my ($a, $b, $c, $d, $e) = 1, 0, False, True, 'pi'; 661say $a && $b && $c; # OUTPUT: «0␤», the first falsey value 662say $a && $b && $c; # OUTPUT: «False␤», the first falsey value 663say $a && $d && $e; # OUTPUT: «pi␤», last operand since everything before is truthy 664 665# `||` returns the first argument that evaluates to `True`. 666say $b || $a || $d; # OUTPUT: «1␤» 667say $e || $d || $a; # OUTPUT: «pi␤» 668 669# And because you're going to want them, you also have compound assignment 670# operators: 671$a *= 2; # multiply and assignment. Equivalent to $a = $a * 2; 672$b %%= 5; # divisible by and assignment. Equivalent to $b = $b %% 2; 673$c div= 3; # return divisor and assignment. Equivalent to $c = $c div 3; 674$d mod= 4; # return remainder and assignment. Equivalent to $d = $d mod 4; 675@array .= sort; # calls the `sort` method and assigns the result back 676 677#################################################### 678# 6. More on subs! 679#################################################### 680 681# As we said before, Raku has *really* powerful subs. We're going 682# to see a few more key concepts that make them better than in any 683# other language :-). 684 685# 686# 6.1 Unpacking! 687# 688 689# Unpacking is the ability to "extract" arrays and keys 690# (AKA "destructuring"). It'll work in `my`s and in parameter lists. 691my ($f, $g) = 1, 2; 692say $f; # OUTPUT: «1␤» 693my ($, $, $h) = 1, 2, 3; # keep the non-interesting values anonymous (`$`) 694say $h; # OUTPUT: «3␤» 695 696my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs" 697my (*@small) = 1; 698 699sub unpack_array( @array [$fst, $snd] ) { 700 say "My first is $fst, my second is $snd! All in all, I'm @array[]."; 701 # (^ remember the `[]` to interpolate the array) 702} 703unpack_array(@tail); 704# OUTPUT: «My first is 2, my second is 3! All in all, I'm 2 3.␤» 705 706# If you're not using the array itself, you can also keep it anonymous, 707# much like a scalar: 708sub first-of-array( @ [$fst] ) { $fst } 709first-of-array(@small); #=> 1 710 711# However calling `first-of-array(@tail);` will throw an error ("Too many 712# positional parameters passed"), which means the `@tail` has too many 713# elements. 714 715# You can also use a slurpy parameter. You could keep `*@rest` anonymous 716# Here, `@rest` is `(3,)`, since `$fst` holds the `2`. This results 717# since the length (.elems) of `@rest` is 1. 718sub slurp-in-array(@ [$fst, *@rest]) { 719 say $fst + @rest.elems; 720} 721slurp-in-array(@tail); # OUTPUT: «3␤» 722 723# You could even extract on a slurpy (but it's pretty useless ;-).) 724sub fst(*@ [$fst]) { # or simply: `sub fst($fst) { ... }` 725 say $fst; 726} 727fst(1); # OUTPUT: «1␤» 728 729# Calling `fst(1, 2);` will throw an error ("Too many positional parameters 730# passed") though. After all, the `fst` sub declares only a single positional 731# parameter. 732 733# You can also destructure hashes (and classes, which you'll learn about later). 734# The syntax is basically the same as 735# `%hash-name (:key($variable-to-store-value-in))`. 736# The hash can stay anonymous if you only need the values you extracted. 737 738# In order to call the function, you must supply a hash wither created with 739# curly braces or with `%()` (recommended). Alternatively, you can pass 740# a variable that contains a hash. 741 742sub key-of( % (:value($val), :qua($qua)) ) { 743 say "Got value $val, $qua time" ~~ 744 $qua == 1 ?? '' !! 's'; 745} 746 747my %foo-once = %(value => 'foo', qua => 1); 748key-of({value => 'foo', qua => 2}); # OUTPUT: «Got val foo, 2 times.␤» 749key-of(%(value => 'foo', qua => 0)); # OUTPUT: «Got val foo, 0 times.␤» 750key-of(%foo-once); # OUTPUT: «Got val foo, 1 time.␤» 751 752# The last expression of a sub is returned automatically (though you may 753# indicate explicitly by using the `return` keyword, of course): 754sub next-index( $n ) { 755 $n + 1; 756} 757my $new-n = next-index(3); # $new-n is now 4 758 759# This is true for everything, except for the looping constructs (due to 760# performance reasons): there's no reason to build a list if we're just going to 761# discard all the results. If you still want to build one, you can use the 762# `do` statement prefix or the `gather` prefix, which we'll see later: 763 764sub list-of( $n ) { 765 do for ^$n { $_ } 766} 767my @list3 = list-of(3); #=> (0, 1, 2) 768 769# 770# 6.2 Lambdas (or anonymous subroutines) 771# 772 773# You can create a lambda by using a pointy block (`-> {}`), a 774# block (`{}`) or creating a `sub` without a name. 775 776my &lambda1 = -> $argument { 777 "The argument passed to this lambda is $argument" 778} 779 780my &lambda2 = { 781 "The argument passed to this lambda is $_" 782} 783 784my &lambda3 = sub ($argument) { 785 "The argument passed to this lambda is $argument" 786} 787 788# Both pointy blocks and blocks are pretty much the same thing, except that 789# the former can take arguments, and that the latter can be mistaken as 790# a hash by the parser. That being said, blocks can declare what's known 791# as placeholders parameters through the twigils `$^` (for positional 792# parameters) and `$:` (for named parameters). More on them later on. 793 794my &mult = { $^numbers * $:times } 795say mult 4, :times(6); #=> «24␤» 796 797# Both pointy blocks and blocks are quite versatile when working with functions 798# that accepts other functions such as `map`, `grep`, etc. For example, 799# we add 3 to each value of an array using the `map` function with a lambda: 800my @nums = 1..4; 801my @res1 = map -> $v { $v + 3 }, @nums; # pointy block, explicit parameter 802my @res2 = map { $_ + 3 }, @nums; # block using an implicit parameter 803my @res3 = map { $^val + 3 }, @nums; # block with placeholder parameter 804 805# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): 806# A block doesn't have a "function context" (though it can have arguments), 807# which means that if you return from it, you're going to return from the 808# parent function. 809 810# Compare: 811sub is-in( @array, $elem ) { 812 say map({ return True if $_ == $elem }, @array); 813 say 'Hi'; 814} 815 816# with: 817sub truthy-array( @array ) { 818 say map sub ($i) { $i ?? return True !! return False }, @array; 819 say 'Hi'; 820} 821 822# In the `is-in` sub, the block will `return` out of the `is-in` sub once the 823# condition evaluates to `True`, the loop won't be run anymore and the 824# following statement won't be executed. The last statement is only executed 825# if the block never returns. 826 827# On the contrary, the `truthy-array` sub will produce an array of `True` and 828# `False`, which will printed, and always execute the last execute statement. 829# Thus, the `return` only returns from the anonymous `sub` 830 831# The `anon` declarator can be used to create an anonymous sub from a 832# regular subroutine. The regular sub knows its name but its symbol is 833# prevented from getting installed in the lexical scope, the method table 834# and everywhere else. 835my $anon-sum = anon sub summation(*@a) { [+] @a } 836say $anon-sum.name; # OUTPUT: «summation␤» 837say $anon-sum(2, 3, 5); # OUTPUT: «10␤» 838#say summation; # Error: Undeclared routine: ... 839 840# You can also use the Whatever Star to create an anonymous subroutine. 841# (it'll stop at the furthest operator in the current expression). 842# The following is the same as `{$_ + 3 }`, `-> { $a + 3 }`, 843# `sub ($a) { $a + 3 }`, or even `{$^a + 3}` (more on this later). 844my @arrayplus3v0 = map * + 3, @nums; 845 846# The following is the same as `-> $a, $b { $a + $b + 3 }`, 847# `sub ($a, $b) { $a + $b + 3 }`, or `{ $^a + $^b + 3 }` (more on this later). 848my @arrayplus3v1 = map * + * + 3, @nums; 849 850say (*/2)(4); # OUTPUT: «2␤», immediately execute the Whatever function created. 851say ((*+3)/5)(5); # OUTPUT: «1.6␤», it works even in parens! 852 853# But if you need to have more than one argument (`$_`) in a block (without 854# wanting to resort to `-> {}`), you can also either `$^` and `$:` which 855# declared placeholder parameters or self-declared positional/named parameters. 856say map { $^a + $^b + 3 }, @nums; 857 858# which is equivalent to the following which uses a `sub`: 859map sub ($a, $b) { $a + $b + 3 }, @nums; 860 861# Placeholder parameters are sorted lexicographically so the following two 862# statements are equivalent: 863say sort { $^b <=> $^a }, @nums; 864say sort -> $a, $b { $b <=> $a }, @nums; 865 866# 867# 6.3 Multiple Dispatch 868# 869 870# Raku can decide which variant of a `sub` to call based on the type of the 871# arguments, or on arbitrary preconditions, like with a type or `where`: 872 873# with types: 874multi sub sayit( Int $n ) { # note the `multi` keyword here 875 say "Number: $n"; 876} 877multi sayit( Str $s ) { # a multi is a `sub` by default 878 say "String: $s"; 879} 880sayit "foo"; # OUTPUT: «String: foo␤» 881sayit 25; # OUTPUT: «Number: 25␤» 882sayit True; # fails at *compile time* with "calling 'sayit' will never 883 # work with arguments of types ..." 884 885# with arbitrary preconditions (remember subsets?): 886multi is-big(Int $n where * > 50) { "Yes!" } # using a closure 887multi is-big(Int $n where {$_ > 50}) { "Yes!" } # similar to above 888multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching 889multi is-big(Int $) { "No" } 890 891subset Even of Int where * %% 2; 892multi odd-or-even(Even) { "Even" } # Using the type. We don't name the argument. 893multi odd-or-even($) { "Odd" } # "everything else" hence the $ variable 894 895# You can even dispatch based on the presence of positional and named arguments: 896multi with-or-without-you($with) { 897 say "I wish I could but I can't"; 898} 899multi with-or-without-you(:$with) { 900 say "I can live! Actually, I can't."; 901} 902multi with-or-without-you { 903 say "Definitely can't live."; 904} 905 906# This is very, very useful for many purposes, like `MAIN` subs (covered 907# later), and even the language itself uses it in several places. 908 909# For example, the `is` trait is actually a `multi sub` named `trait_mod:<is>`, 910# and it works off that. Thus, `is rw`, is simply a dispatch to a function with 911# this signature `sub trait_mod:<is>(Routine $r, :$rw!) {}` 912 913#################################################### 914# 7. About types... 915#################################################### 916 917# Raku is gradually typed. This means you can specify the type of your 918# variables/arguments/return types, or you can omit the type annotations in 919# in which case they'll default to `Any`. Obviously you get access to a few 920# base types, like `Int` and `Str`. The constructs for declaring types are 921# `subset`, `class`, `role`, etc. which you'll see later. 922 923# For now, let us examine `subset` which is a "sub-type" with additional 924# checks. For example, "a very big integer is an `Int` that's greater than 500". 925# You can specify the type you're subtyping (by default, `Any`), and add 926# additional checks with the `where` clause. 927subset VeryBigInteger of Int where * > 500; 928 929# Or the set of the whole numbers: 930subset WholeNumber of Int where * >= 0; 931my WholeNumber $whole-six = 6; # OK 932#my WholeNumber $nonwhole-one = -1; # Error: type check failed... 933 934# Or the set of Positive Even Numbers whose Mod 5 is 1. Notice we're 935# using the previously defined WholeNumber subset. 936subset PENFO of WholeNumber where { $_ %% 2 and $_ mod 5 == 1 }; 937my PENFO $yes-penfo = 36; # OK 938#my PENFO $no-penfo = 2; # Error: type check failed... 939 940#################################################### 941# 8. Scoping 942#################################################### 943 944# In Raku, unlike many scripting languages, (such as Python, Ruby, PHP), 945# you must declare your variables before using them. The `my` declarator 946# we've used so far uses "lexical scoping". There are a few other declarators, 947# (`our`, `state`, ..., ) which we'll see later. This is called 948# "lexical scoping", where in inner blocks, you can access variables from 949# outer blocks. 950 951my $file_scoped = 'Foo'; 952sub outer { 953 my $outer_scoped = 'Bar'; 954 sub inner { 955 say "$file_scoped $outer_scoped"; 956 } 957 &inner; # return the function 958} 959outer()(); # OUTPUT: «Foo Bar␤» 960 961# As you can see, `$file_scoped` and `$outer_scoped` were captured. 962# But if we were to try and use `$outer_scoped` outside the `outer` sub, 963# the variable would be undefined (and you'd get a compile time error). 964 965#################################################### 966# 9. Twigils 967#################################################### 968 969# There are many special `twigils` (composed sigils) in Raku. Twigils 970# define a variable's scope. 971# The `*` and `?` twigils work on standard variables: 972# * for dynamic variables 973# ? for compile-time variables 974# 975# The `!` and the `.` twigils are used with Raku's objects: 976# ! for attributes (instance attribute) 977# . for methods (not really a variable) 978 979# 980# `*` twigil: Dynamic Scope 981# 982 983# These variables use the `*` twigil to mark dynamically-scoped variables. 984# Dynamically-scoped variables are looked up through the caller, not through 985# the outer scope. 986 987my $*dyn_scoped_1 = 1; 988my $*dyn_scoped_2 = 10; 989 990sub say_dyn { 991 say "$*dyn_scoped_1 $*dyn_scoped_2"; 992} 993 994sub call_say_dyn { 995 # Defines $*dyn_scoped_1 only for this sub. 996 my $*dyn_scoped_1 = 25; 997 998 # Will change the value of the file scoped variable. 999 $*dyn_scoped_2 = 100; 1000 1001 # $*dyn_scoped 1 and 2 will be looked for in the call. 1002 say_dyn(); # OUTPUT: «25 100␤» 1003 1004 # The call to `say_dyn` uses the value of $*dyn_scoped_1 from inside 1005 # this sub's lexical scope even though the blocks aren't nested (they're 1006 # call-nested). 1007} 1008say_dyn(); # OUTPUT: «1 10␤» 1009 1010# Uses $*dyn_scoped_1 as defined in `call_say_dyn` even though we are calling it 1011# from outside. 1012call_say_dyn(); # OUTPUT: «25 100␤» 1013 1014# We changed the value of $*dyn_scoped_2 in `call_say_dyn` so now its 1015# value has changed. 1016say_dyn(); # OUTPUT: «1 100␤» 1017 1018# TODO: Add information about remaining twigils 1019 1020#################################################### 1021# 10. Object Model 1022#################################################### 1023 1024# To call a method on an object, add a dot followed by the method name: 1025# `$object.method` 1026 1027# Classes are declared with the `class` keyword. Attributes are declared 1028# with the `has` keyword, and methods declared with the `method` keyword. 1029 1030# Every attribute that is private uses the `!` twigil. For example: `$!attr`. 1031# Immutable public attributes use the `.` twigil which creates a read-only 1032# method named after the attribute. In fact, declaring an attribute with `.` 1033# is equivalent to declaring the same attribute with `!` and then creating 1034# a read-only method with the attribute's name. However, this is done for us 1035# by Raku automatically. The easiest way to remember the `$.` twigil is 1036# by comparing it to how methods are called. 1037 1038# Raku's object model ("SixModel") is very flexible, and allows you to 1039# dynamically add methods, change semantics, etc... Unfortunately, these will 1040# not all be covered here, and you should refer to: 1041# https://docs.raku.org/language/objects.html. 1042 1043class Human { 1044 has Str $.name; # `$.name` is immutable but with an accessor method. 1045 has Str $.bcountry; # Use `$!bcountry` to modify it inside the class. 1046 has Str $.ccountry is rw; # This attribute can be modified from outside. 1047 has Int $!age = 0; # A private attribute with default value. 1048 1049 method birthday { 1050 $!age += 1; # Add a year to human's age 1051 } 1052 1053 method get-age { 1054 return $!age; 1055 } 1056 1057 # This method is private to the class. Note the `!` before the 1058 # method's name. 1059 method !do-decoration { 1060 return "$!name born in $!bcountry and now lives in $!ccountry." 1061 } 1062 1063 # This method is public, just like `birthday` and `get-age`. 1064 method get-info { 1065 # Invoking a method on `self` inside the class. 1066 # Use `self!priv-method` for private method. 1067 say self!do-decoration; 1068 1069 # Use `self.public-method` for public method. 1070 say "Age: ", self.get-age; 1071 } 1072}; 1073 1074# Create a new instance of Human class. 1075# NOTE: Only attributes declared with the `.` twigil can be set via the 1076# default constructor (more later on). This constructor only accepts named 1077# arguments. 1078my $person1 = Human.new( 1079 name => "Jord", 1080 bcountry => "Togo", 1081 ccountry => "Togo" 1082); 1083 1084# Make human 10 years old. 1085$person1.birthday for 1..10; 1086 1087say $person1.name; # OUTPUT: «Jord␤» 1088say $person1.bcountry; # OUTPUT: «Togo␤» 1089say $person1.ccountry; # OUTPUT: «Togo␤» 1090say $person1.get-age; # OUTPUT: «10␤» 1091 1092# This fails, because the `has $.bcountry`is immutable. Jord can't change 1093# his birthplace. 1094# $person1.bcountry = "Mali"; 1095 1096# This works because the `$.ccountry` is mutable (`is rw`). Now Jord's 1097# current country is France. 1098$person1.ccountry = "France"; 1099 1100# Calling methods on the instance objects. 1101$person1.birthday; #=> 1 1102$person1.get-info; #=> Jord born in Togo and now lives in France. Age: 10 1103# $person1.do-decoration; # This fails since the method `do-decoration` is private. 1104 1105# 1106# 10.1 Object Inheritance 1107# 1108 1109# Raku also has inheritance (along with multiple inheritance). While 1110# methods are inherited, submethods are not. Submethods are useful for 1111# object construction and destruction tasks, such as `BUILD`, or methods that 1112# must be overridden by subtypes. We will learn about `BUILD` later on. 1113 1114class Parent { 1115 has $.age; 1116 has $.name; 1117 1118 # This submethod won't be inherited by the Child class. 1119 submethod favorite-color { 1120 say "My favorite color is Blue"; 1121 } 1122 1123 # This method is inherited 1124 method talk { say "Hi, my name is $!name" } 1125} 1126 1127# Inheritance uses the `is` keyword 1128class Child is Parent { 1129 method talk { say "Goo goo ga ga" } 1130 # This shadows Parent's `talk` method. 1131 # This child hasn't learned to speak yet! 1132} 1133 1134my Parent $Richard .= new(age => 40, name => 'Richard'); 1135$Richard.favorite-color; # OUTPUT: «My favorite color is Blue␤» 1136$Richard.talk; # OUTPUT: «Hi, my name is Richard␤» 1137# $Richard is able to access the submethod and he knows how to say his name. 1138 1139my Child $Madison .= new(age => 1, name => 'Madison'); 1140$Madison.talk; # OUTPUT: «Goo goo ga ga␤», due to the overridden method. 1141# $Madison.favorite-color # does not work since it is not inherited. 1142 1143# When you use `my T $var`, `$var` starts off with `T` itself in it, so you can 1144# call `new` on it. (`.=` is just the dot-call and the assignment operator). 1145# Thus, `$a .= b` is the same as `$a = $a.b`. Also note that `BUILD` (the method 1146# called inside `new`) will set parent's properties too, so you can pass `val => 1147# 5`. 1148 1149# 1150# 10.2 Roles, or Mixins 1151# 1152 1153# Roles are supported too (which are called Mixins in other languages) 1154role PrintableVal { 1155 has $!counter = 0; 1156 method print { 1157 say $.val; 1158 } 1159} 1160 1161# you "apply" a role (or mixin) with the `does` keyword: 1162class Item does PrintableVal { 1163 has $.val; 1164 1165 =begin comment 1166 When `does`-ed, a `role` literally "mixes in" the class: 1167 the methods and attributes are put together, which means a class 1168 can access the private attributes/methods of its roles (but 1169 not the inverse!): 1170 =end comment 1171 method access { 1172 say $!counter++; 1173 } 1174 1175 =begin comment 1176 However, this: method print {} is ONLY valid when `print` isn't a `multi` 1177 with the same dispatch. This means a parent class can shadow a child class's 1178 `multi print() {}`, but it's an error if a role does) 1179 1180 NOTE: You can use a role as a class (with `is ROLE`). In this case, 1181 methods will be shadowed, since the compiler will consider `ROLE` 1182 to be a class. 1183 =end comment 1184} 1185 1186#################################################### 1187# 11. Exceptions 1188#################################################### 1189 1190# Exceptions are built on top of classes, in the package `X` (like `X::IO`). 1191# In Raku, exceptions are automatically 'thrown': 1192 1193# open 'foo'; # OUTPUT: «Failed to open file foo: no such file or directory␤» 1194 1195# It will also print out what line the error was thrown at 1196# and other error info. 1197 1198# You can throw an exception using `die`. Here it's been commented out to 1199# avoid stopping the program's execution: 1200# die 'Error!'; # OUTPUT: «Error!␤» 1201 1202# Or more explicitly (commented out too): 1203# X::AdHoc.new(payload => 'Error!').throw; # OUTPUT: «Error!␤» 1204 1205# In Raku, `orelse` is similar to the `or` operator, except it only matches 1206# undefined variables instead of anything evaluating as `False`. 1207# Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str` 1208# and other types that have not been initialized to any value yet. 1209# You can check if something is defined or not using the defined method: 1210my $uninitialized; 1211say $uninitialized.defined; # OUTPUT: «False␤» 1212 1213# When using `orelse` it will disarm the exception and alias $_ to that 1214# failure. This will prevent it to being automatically handled and printing 1215# lots of scary error messages to the screen. We can use the `exception` 1216# method on the `$_` variable to access the exception 1217open 'foo' orelse say "Something happened {.exception}"; 1218 1219# This also works: 1220open 'foo' orelse say "Something happened $_"; 1221# OUTPUT: «Something happened Failed to open file foo: no such file or directory␤» 1222 1223# Both of those above work but in case we get an object from the left side 1224# that is not a failure we will probably get a warning. We see below how we 1225# can use try` and `CATCH` to be more specific with the exceptions we catch. 1226 1227# 1228# 11.1 Using `try` and `CATCH` 1229# 1230 1231# By using `try` and `CATCH` you can contain and handle exceptions without 1232# disrupting the rest of the program. The `try` block will set the last 1233# exception to the special variable `$!` (known as the error variable). 1234# NOTE: This has no relation to $!variables seen inside class definitions. 1235 1236try open 'foo'; 1237say "Well, I tried! $!" if defined $!; 1238# OUTPUT: «Well, I tried! Failed to open file foo: no such file or directory␤» 1239 1240# Now, what if we want more control over handling the exception? 1241# Unlike many other languages, in Raku, you put the `CATCH` block *within* 1242# the block to `try`. Similar to how the `$_` variable was set when we 1243# 'disarmed' the exception with `orelse`, we also use `$_` in the CATCH block. 1244# NOTE: The `$!` variable is only set *after* the `try` block has caught an 1245# exception. By default, a `try` block has a `CATCH` block of its own that 1246# catches any exception (`CATCH { default {} }`). 1247 1248try { 1249 my $a = (0 %% 0); 1250 CATCH { 1251 default { say "Something happened: $_" } 1252 } 1253} 1254# OUTPUT: «Something happened: Attempt to divide by zero using infix:<%%>␤» 1255 1256# You can redefine it using `when`s (and `default`) to handle the exceptions 1257# you want to catch explicitly: 1258 1259try { 1260 open 'foo'; 1261 CATCH { 1262 # In the `CATCH` block, the exception is set to the $_ variable. 1263 when X::AdHoc { 1264 say "Error: $_" 1265 } 1266 when X::Numeric::DivideByZero { 1267 say "Error: $_"; 1268 } 1269 1270 =begin comment 1271 Any other exceptions will be re-raised, since we don't have a `default`. 1272 Basically, if a `when` matches (or there's a `default`), the 1273 exception is marked as "handled" so as to prevent its re-throw 1274 from the `CATCH` block. You still can re-throw the exception 1275 (see below) by hand. 1276 =end comment 1277 default { 1278 say "Any other error: $_" 1279 } 1280 } 1281} 1282# OUTPUT: «Failed to open file /dir/foo: no such file or directory␤» 1283 1284# There are also some subtleties to exceptions. Some Raku subs return a 1285# `Failure`, which is a wrapper around an `Exception` object which is 1286# "unthrown". They're not thrown until you try to use the variables containing 1287# them unless you call `.Bool`/`.defined` on them - then they're handled. 1288# (the `.handled` method is `rw`, so you can mark it as `False` back yourself) 1289# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal` 1290# is on, `fail` will throw an exception (like `die`). 1291 1292my $value = 0/0; # We're not trying to access the value, so no problem. 1293try { 1294 say 'Value: ', $value; # Trying to use the value 1295 CATCH { 1296 default { 1297 say "It threw because we tried to get the fail's value!" 1298 } 1299 } 1300} 1301 1302# There is also another kind of exception: Control exceptions. Those are "good" 1303# exceptions, which happen when you change your program's flow, using operators 1304# like `return`, `next` or `last`. You can "catch" those with `CONTROL` (not 100% 1305# working in Rakudo yet). 1306 1307#################################################### 1308# 12. Packages 1309#################################################### 1310 1311# Packages are a way to reuse code. Packages are like "namespaces", and any 1312# element of the six model (`module`, `role`, `class`, `grammar`, `subset` and 1313# `enum`) are actually packages. (Packages are the lowest common denominator) 1314# Packages are important - especially as Perl is well-known for CPAN, 1315# the Comprehensive Perl Archive Network. 1316 1317# You can use a module (bring its declarations into scope) with `use`: 1318use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module 1319say from-json('[1]').perl; # OUTPUT: «[1]␤» 1320 1321# You should not declare packages using the `package` keyword (unlike Perl). 1322# Instead, use `class Package::Name::Here;` to declare a class, or if you only 1323# want to export variables/subs, you can use `module` instead. 1324 1325# If `Hello` doesn't exist yet, it'll just be a "stub", that can be redeclared 1326# as something else later. 1327module Hello::World { # bracketed form 1328 # declarations here 1329} 1330 1331# The file-scoped form which extends until the end of the file. For 1332# instance, `unit module Parse::Text;` will extend until of the file. 1333 1334# A grammar is a package, which you could `use`. You will learn more about 1335# grammars in the regex section. 1336grammar Parse::Text::Grammar { 1337} 1338 1339# As said before, any part of the six model is also a package. 1340# Since `JSON::Tiny` uses its own `JSON::Tiny::Actions` class, you can use it: 1341my $actions = JSON::Tiny::Actions.new; 1342 1343# We'll see how to export variables and subs in the next part. 1344 1345#################################################### 1346# 13. Declarators 1347#################################################### 1348 1349# In Raku, you get different behaviors based on how you declare a variable. 1350# You've already seen `my` and `has`, we'll now explore the others. 1351 1352# `our` - these declarations happen at `INIT` time -- (see "Phasers" below). 1353# It's like `my`, but it also creates a package variable. All packagish 1354# things such as `class`, `role`, etc. are `our` by default. 1355 1356module Var::Increment { 1357 # NOTE: `our`-declared variables cannot be typed. 1358 our $our-var = 1; 1359 my $my-var = 22; 1360 1361 our sub Inc { 1362 our sub available { # If you try to make inner `sub`s `our`... 1363 # ... Better know what you're doing (Don't !). 1364 say "Don't do that. Seriously. You'll get burned."; 1365 } 1366 1367 my sub unavailable { # `sub`s are `my`-declared by default 1368 say "Can't access me from outside, I'm 'my'!"; 1369 } 1370 say ++$our-var; # Increment the package variable and output its value 1371 } 1372 1373} 1374 1375say $Var::Increment::our-var; # OUTPUT: «1␤», this works! 1376say $Var::Increment::my-var; # OUTPUT: «(Any)␤», this will not work! 1377 1378say Var::Increment::Inc; # OUTPUT: «2␤» 1379say Var::Increment::Inc; # OUTPUT: «3␤», notice how the value of $our-var was retained. 1380 1381# Var::Increment::unavailable; # OUTPUT: «Could not find symbol '&unavailable'␤» 1382 1383# `constant` - these declarations happen at `BEGIN` time. You can use 1384# the `constant` keyword to declare a compile-time variable/symbol: 1385constant Pi = 3.14; 1386constant $var = 1; 1387 1388# And if you're wondering, yes, it can also contain infinite lists. 1389constant why-not = 5, 15 ... *; 1390say why-not[^5]; # OUTPUT: «5 15 25 35 45␤» 1391 1392# `state` - these declarations happen at run time, but only once. State 1393# variables are only initialized one time. In other languages such as C 1394# they exist as `static` variables. 1395sub fixed-rand { 1396 state $val = rand; 1397 say $val; 1398} 1399fixed-rand for ^10; # will print the same number 10 times 1400 1401# Note, however, that they exist separately in different enclosing contexts. 1402# If you declare a function with a `state` within a loop, it'll re-create the 1403# variable for each iteration of the loop. See: 1404for ^5 -> $a { 1405 sub foo { 1406 # This will be a different value for every value of `$a` 1407 state $val = rand; 1408 } 1409 for ^5 -> $b { 1410 # This will print the same value 5 times, but only 5. Next iteration 1411 # will re-run `rand`. 1412 say foo; 1413 } 1414} 1415 1416#################################################### 1417# 14. Phasers 1418#################################################### 1419 1420# Phasers in Raku are blocks that happen at determined points of time in 1421# your program. They are called phasers because they mark a change in the 1422# phase of a program. For example, when the program is compiled, a for loop 1423# runs, you leave a block, or an exception gets thrown (The `CATCH` block is 1424# actually a phaser!). Some of them can be used for their return values, 1425# some of them can't (those that can have a "[*]" in the beginning of their 1426# explanation text). Let's have a look! 1427 1428# 1429# 14.1 Compile-time phasers 1430# 1431BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } 1432CHECK { say "[*] Runs at compile time, as late as possible, only once" } 1433 1434# 1435# 14.2 Run-time phasers 1436# 1437INIT { say "[*] Runs at run time, as soon as possible, only once" } 1438END { say "Runs at run time, as late as possible, only once" } 1439 1440# 1441# 14.3 Block phasers 1442# 1443ENTER { say "[*] Runs every time you enter a block, repeats on loop blocks" } 1444LEAVE { 1445 say "Runs every time you leave a block, even when an exception 1446 happened. Repeats on loop blocks." 1447} 1448 1449PRE { 1450 say "Asserts a precondition at every block entry, 1451 before ENTER (especially useful for loops)"; 1452 say "If this block doesn't return a truthy value, 1453 an exception of type X::Phaser::PrePost is thrown."; 1454} 1455 1456# Example (commented out): 1457for 0..2 { 1458 # PRE { $_ > 1 } # OUTPUT: «Precondition '{ $_ > 1 }' failed 1459} 1460 1461POST { 1462 say "Asserts a postcondition at every block exit, 1463 after LEAVE (especially useful for loops)"; 1464 say "If this block doesn't return a truthy value, 1465 an exception of type X::Phaser::PrePost is thrown, like PRE."; 1466} 1467 1468# Example (commented out): 1469for 0..2 { 1470 # POST { $_ < 1 } # OUTPUT: «Postcondition '{ $_ < 1 }' failed 1471} 1472 1473# 1474# 14.4 Block/exceptions phasers 1475# 1476{ 1477 KEEP { say "Runs when you exit a block successfully 1478 (without throwing an exception)" } 1479 UNDO { say "Runs when you exit a block unsuccessfully 1480 (by throwing an exception)" } 1481} 1482 1483# 1484# 14.5 Loop phasers 1485# 1486for ^5 { 1487 FIRST { say "[*] The first time the loop is run, before ENTER" } 1488 NEXT { say "At loop continuation time, before LEAVE" } 1489 LAST { say "At loop termination time, after LEAVE" } 1490} 1491 1492# 1493# 14.6 Role/class phasers 1494# 1495COMPOSE { 1496 say "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" 1497} 1498 1499# They allow for cute tricks or clever code...: 1500say "This code took " ~ (time - CHECK time) ~ "s to compile"; 1501 1502# ... or clever organization: 1503class DB { 1504 method start-transaction { say "Starting transaction!" } 1505 method commit { say "Committing transaction..." } 1506 method rollback { say "Something went wrong. Rolling back!" } 1507} 1508 1509sub do-db-stuff { 1510 my DB $db .= new; 1511 $db.start-transaction; # start a new transaction 1512 KEEP $db.commit; # commit the transaction if all went well 1513 UNDO $db.rollback; # or rollback if all hell broke loose 1514} 1515 1516do-db-stuff(); 1517 1518#################################################### 1519# 15. Statement prefixes 1520#################################################### 1521 1522# Those act a bit like phasers: they affect the behavior of the following 1523# code. Though, they run in-line with the executable code, so they're in 1524# lowercase. (`try` and `start` are theoretically in that list, but explained 1525# elsewhere) NOTE: all of these (except start) don't need explicit curly 1526# braces `{` and `}`. 1527 1528# 1529# 15.1 `do` - It runs a block or a statement as a term. 1530# 1531 1532# Normally you cannot use a statement as a value (or "term"). `do` helps 1533# us do it. With `do`, an `if`, for example, becomes a term returning a value. 1534=for comment :reason<this fails since `if` is a statement> 1535my $value = if True { 1 } 1536 1537# this works! 1538my $get-five = do if True { 5 } 1539 1540# 1541# 15.1 `once` - makes sure a piece of code only runs once. 1542# 1543for ^5 { 1544 once say 1 1545}; 1546# OUTPUT: «1␤», only prints ... once 1547 1548# Similar to `state`, they're cloned per-scope. 1549for ^5 { 1550 sub { once say 1 }() 1551}; 1552# OUTPUT: «1 1 1 1 1␤», prints once per lexical scope. 1553 1554# 1555# 15.2 `gather` - co-routine thread. 1556# 1557 1558# The `gather` constructs allows us to `take` several values from an array/list, 1559# much like `do`. 1560say gather for ^5 { 1561 take $_ * 3 - 1; 1562 take $_ * 3 + 1; 1563} 1564# OUTPUT: «-1 1 2 4 5 7 8 10 11 13␤» 1565 1566say join ',', gather if False { 1567 take 1; 1568 take 2; 1569 take 3; 1570} 1571# Doesn't print anything. 1572 1573# 1574# 15.3 `eager` - evaluates a statement eagerly (forces eager context). 1575 1576# Don't try this at home. This will probably hang for a while (and might crash) 1577# so commented out. 1578# eager 1..*; 1579 1580# But consider, this version which doesn't print anything 1581constant thricev0 = gather for ^3 { say take $_ }; 1582# to: 1583constant thricev1 = eager gather for ^3 { say take $_ }; # OUTPUT: «0 1 2␤» 1584 1585#################################################### 1586# 16. Iterables 1587#################################################### 1588 1589# Iterables are objects that can be iterated over for things such as 1590# the `for` construct. 1591 1592# 1593# 16.1 `flat` - flattens iterables. 1594# 1595say (1, 10, (20, 10) ); # OUTPUT: «(1 10 (20 10))␤», notice how nested 1596 # lists are preserved 1597say (1, 10, (20, 10) ).flat; # OUTPUT: «(1 10 20 10)␤», now the iterable is flat 1598 1599# 1600# 16.2 `lazy` - defers actual evaluation until value is fetched by forcing lazy context. 1601# 1602my @lazy-array = (1..100).lazy; 1603say @lazy-array.is-lazy; # OUTPUT: «True␤», check for laziness with the `is-lazy` method. 1604 1605say @lazy-array; # OUTPUT: «[...]␤», List has not been iterated on! 1606 1607# This works and will only do as much work as is needed. 1608for @lazy-array { .print }; 1609 1610# (**TODO** explain that gather/take and map are all lazy) 1611 1612# 1613# 16.3 `sink` - an `eager` that discards the results by forcing sink context. 1614# 1615constant nilthingie = sink for ^3 { .say } #=> 0 1 2 1616say nilthingie.perl; # OUTPUT: «Nil␤» 1617 1618# 1619# 16.4 `quietly` - suppresses warnings in blocks. 1620# 1621quietly { warn 'This is a warning!' }; # No output 1622 1623#################################################### 1624# 17. More operators thingies! 1625#################################################### 1626 1627# Everybody loves operators! Let's get more of them. 1628 1629# The precedence list can be found here: 1630# https://docs.raku.org/language/operators#Operator_Precedence 1631# But first, we need a little explanation about associativity: 1632 1633# 1634# 17.1 Binary operators 1635# 1636 1637my ($p, $q, $r) = (1, 2, 3); 1638 1639# Given some binary operator § (not a Raku-supported operator), then: 1640 1641# $p § $q § $r; # with a left-associative §, this is ($p § $q) § $r 1642# $p § $q § $r; # with a right-associative §, this is $p § ($q § $r) 1643# $p § $q § $r; # with a non-associative §, this is illegal 1644# $p § $q § $r; # with a chain-associative §, this is ($p § $q) and ($q § $r)§ 1645# $p § $q § $r; # with a list-associative §, this is `infix:<>` 1646 1647# 1648# 17.2 Unary operators 1649# 1650 1651# Given some unary operator § (not a Raku-supported operator), then: 1652# §$p§ # with left-associative §, this is (§$p)§ 1653# §$p§ # with right-associative §, this is §($p§) 1654# §$p§ # with non-associative §, this is illegal 1655 1656# 1657# 17.3 Create your own operators! 1658# 1659 1660# Okay, you've been reading all of that, so you might want to try something 1661# more exciting?! I'll tell you a little secret (or not-so-secret): 1662# In Raku, all operators are actually just funny-looking subroutines. 1663 1664# You can declare an operator just like you declare a sub. In the following 1665# example, `prefix` refers to the operator categories (prefix, infix, postfix, 1666# circumfix, and post-circumfix). 1667sub prefix:<win>( $winner ) { 1668 say "$winner Won!"; 1669} 1670win "The King"; # OUTPUT: «The King Won!␤» 1671 1672# you can still call the sub with its "full name": 1673say prefix:<!>(True); # OUTPUT: «False␤» 1674prefix:<win>("The Queen"); # OUTPUT: «The Queen Won!␤» 1675 1676sub postfix:<!>( Int $n ) { 1677 [*] 2..$n; # using the reduce meta-operator... See below ;-)! 1678} 1679say 5!; # OUTPUT: «120␤» 1680 1681# Postfix operators ('after') have to come *directly* after the term. 1682# No whitespace. You can use parentheses to disambiguate, i.e. `(5!)!` 1683 1684sub infix:<times>( Int $n, Block $r ) { # infix ('between') 1685 for ^$n { 1686 # You need the explicit parentheses to call the function in `$r`, 1687 # else you'd be referring at the code object itself, like with `&r`. 1688 $r(); 1689 } 1690} 16913 times -> { say "hello" }; # OUTPUT: «hello␤hello␤hello␤» 1692 1693# It's recommended to put spaces around your infix operator calls. 1694 1695# For circumfix and post-circumfix ones 1696multi circumfix:<[ ]>( Int $n ) { 1697 $n ** $n 1698} 1699say [5]; # OUTPUT: «3125␤» 1700 1701# Circumfix means 'around'. Again, no whitespace. 1702 1703multi postcircumfix:<{ }>( Str $s, Int $idx ) { 1704 $s.substr($idx, 1); 1705} 1706say "abc"{1}; # OUTPUT: «b␤», after the term `"abc"`, and around the index (1) 1707 1708# Post-circumfix is 'after a term, around something' 1709 1710# This really means a lot -- because everything in Raku uses this. 1711# For example, to delete a key from a hash, you use the `:delete` adverb 1712# (a simple named argument underneath). For instance, the following statements 1713# are equivalent. 1714my %person-stans = 1715 'Giorno Giovanna' => 'Gold Experience', 1716 'Bruno Bucciarati' => 'Sticky Fingers'; 1717my $key = 'Bruno Bucciarati'; 1718%person-stans{$key}:delete; 1719postcircumfix:<{ }>( %person-stans, 'Giorno Giovanna', :delete ); 1720# (you can call operators like this) 1721 1722# It's *all* using the same building blocks! Syntactic categories 1723# (prefix infix ...), named arguments (adverbs), ..., etc. used to build 1724# the language - are available to you. Obviously, you're advised against 1725# making an operator out of *everything* -- with great power comes great 1726# responsibility. 1727 1728# 1729# 17.4 Meta operators! 1730# 1731 1732# Oh boy, get ready!. Get ready, because we're delving deep into the rabbit's 1733# hole, and you probably won't want to go back to other languages after 1734# reading this. (I'm guessing you don't want to go back at this point but 1735# let's continue, for the journey is long and enjoyable!). 1736 1737# Meta-operators, as their name suggests, are *composed* operators. Basically, 1738# they're operators that act on another operators. 1739 1740# The reduce meta-operator is a prefix meta-operator that takes a binary 1741# function and one or many lists. If it doesn't get passed any argument, 1742# it either returns a "default value" for this operator (a meaningless value) 1743# or `Any` if there's none (examples below). Otherwise, it pops an element 1744# from the list(s) one at a time, and applies the binary function to the last 1745# result (or the first element of a list) and the popped element. 1746 1747# To sum a list, you could use the reduce meta-operator with `+`, i.e.: 1748say [+] 1, 2, 3; # OUTPUT: «6␤», equivalent to (1+2)+3. 1749 1750# To multiply a list 1751say [*] 1..5; # OUTPUT: «120␤», equivalent to ((((1*2)*3)*4)*5). 1752 1753# You can reduce with any operator, not just with mathematical ones. 1754# For example, you could reduce with `//` to get first defined element 1755# of a list: 1756say [//] Nil, Any, False, 1, 5; # OUTPUT: «False␤» 1757 # (Falsey, but still defined) 1758# Or with relational operators, i.e., `>` to check elements of a list 1759# are ordered accordingly: 1760say [>] 234, 156, 6, 3, -20; # OUTPUT: «True␤» 1761 1762# Default value examples: 1763say [*] (); # OUTPUT: «1␤», empty product 1764say [+] (); # OUTPUT: «0␤», empty sum 1765say [//]; # OUTPUT: «(Any)␤» 1766 # There's no "default value" for `//`. 1767 1768# You can also use it with a function you made up, 1769# You can also surround using double brackets: 1770sub add($a, $b) { $a + $b } 1771say [[&add]] 1, 2, 3; # OUTPUT: «6␤» 1772 1773# The zip meta-operator is an infix meta-operator that also can be used as a 1774# "normal" operator. It takes an optional binary function (by default, it 1775# just creates a pair), and will pop one value off of each array and call 1776# its binary function on these until it runs out of elements. It returns an 1777# array with all of these new elements. 1778say (1, 2) Z (3, 4); # OUTPUT: «((1, 3), (2, 4))␤» 1779say 1..3 Z+ 4..6; # OUTPUT: «(5, 7, 9)␤» 1780 1781# Since `Z` is list-associative (see the list above), you can use it on more 1782# than one list. 1783(True, False) Z|| (False, False) Z|| (False, False); # (True, False) 1784 1785# And, as it turns out, you can also use the reduce meta-operator with it: 1786[Z||] (True, False), (False, False), (False, False); # (True, False) 1787 1788# And to end the operator list: 1789 1790# The sequence operator (`...`) is one of Raku's most powerful features: 1791# It's composed by the list (which might include a closure) you want Raku to 1792# deduce from on the left and a value (or either a predicate or a Whatever Star 1793# for a lazy infinite list) on the right that states when to stop. 1794 1795# Basic arithmetic sequence 1796my @listv0 = 1, 2, 3...10; 1797 1798# This dies because Raku can't figure out the end 1799# my @list = 1, 3, 6...10; 1800 1801# As with ranges, you can exclude the last element (the iteration ends when 1802# the predicate matches). 1803my @listv1 = 1, 2, 3...^10; 1804 1805# You can use a predicate (with the Whatever Star). 1806my @listv2 = 1, 3, 9...* > 30; 1807 1808# Equivalent to the example above but using a block here. 1809my @listv3 = 1, 3, 9 ... { $_ > 30 }; 1810 1811# Lazy infinite list of fibonacci sequence, computed using a closure! 1812my @fibv0 = 1, 1, *+* ... *; 1813 1814# Equivalent to the above example but using a pointy block. 1815my @fibv1 = 1, 1, -> $a, $b { $a + $b } ... *; 1816 1817# Equivalent to the above example but using a block with placeholder parameters. 1818my @fibv2 = 1, 1, { $^a + $^b } ... *; 1819 1820# In the examples with explicit parameters (i.e., $a and $b), $a and $b 1821# will always take the previous values, meaning that for the Fibonacci sequence, 1822# they'll start with $a = 1 and $b = 1 (values we set by hand), then $a = 1 1823# and $b = 2 (result from previous $a + $b), and so on. 1824 1825# In the example we use a range as an index to access the sequence. However, 1826# it's worth noting that for ranges, once reified, elements aren't re-calculated. 1827# That's why, for instance, `@primes[^100]` will take a long time the first 1828# time you print it but then it will be instantaneous. 1829say @fibv0[^10]; # OUTPUT: «1 1 2 3 5 8 13 21 34 55␤» 1830 1831#################################################### 1832# 18. Regular Expressions 1833#################################################### 1834 1835# I'm sure a lot of you have been waiting for this one. Well, now that you know 1836# a good deal of Raku already, we can get started. First off, you'll have to 1837# forget about "PCRE regexps" (perl-compatible regexps). 1838 1839# IMPORTANT: Don't skip them because you know PCRE. They're different. Some 1840# things are the same (like `?`, `+`, and `*`), but sometimes the semantics 1841# change (`|`). Make sure you read carefully, because you might trip over a 1842# new behavior. 1843 1844# Raku has many features related to RegExps. After all, Rakudo parses itself. 1845# We're first going to look at the syntax itself, then talk about grammars 1846# (PEG-like), differences between `token`, `regex` and `rule` declarators, 1847# and some more. Side note: you still have access to PCRE regexps using the 1848# `:P5` modifier which we won't be discussing this in this tutorial, though. 1849 1850# In essence, Raku natively implements PEG ("Parsing Expression Grammars"). 1851# The pecking order for ambiguous parses is determined by a multi-level 1852# tie-breaking test: 1853# - Longest token matching: `foo\s+` beats `foo` (by 2 or more positions) 1854# - Longest literal prefix: `food\w*` beats `foo\w*` (by 1) 1855# - Declaration from most-derived to less derived grammars 1856# (grammars are actually classes) 1857# - Earliest declaration wins 1858say so 'a' ~~ /a/; # OUTPUT: «True␤» 1859say so 'a' ~~ / a /; # OUTPUT: «True␤», more readable with some spaces! 1860 1861# In all our examples, we're going to use the smart-matching operator against 1862# a regexp. We're converting the result using `so` to a Boolean value because, 1863# in fact, it's returning a `Match` object. They know how to respond to list 1864# indexing, hash indexing, and return the matched string. The results of the 1865# match are available in the `$/` variable (implicitly lexically-scoped). You 1866# can also use the capture variables which start at 0: `$0`, `$1', `$2`... 1867 1868# You can also note that `~~` does not perform start/end checking, meaning 1869# the regexp can be matched with just one character of the string. We'll 1870# explain later how you can do it. 1871 1872# In Raku, you can have any alphanumeric as a literal, everything else has 1873# to be escaped by using a backslash or quotes. 1874say so 'a|b' ~~ / a '|' b /; # OUTPUT: «True␤», it wouldn't mean the same 1875 # thing if `|` wasn't escaped. 1876say so 'a|b' ~~ / a \| b /; # OUTPUT: «True␤», another way to escape it. 1877 1878# The whitespace in a regex is actually not significant, unless you use the 1879# `:s` (`:sigspace`, significant space) adverb. 1880say so 'a b c' ~~ / a b c /; #=> `False`, space is not significant here! 1881say so 'a b c' ~~ /:s a b c /; #=> `True`, we added the modifier `:s` here. 1882 1883# If we use only one space between strings in a regex, Raku will warn us 1884# about space being not signicant in the regex: 1885say so 'a b c' ~~ / a b c /; # OUTPUT: «False␤» 1886say so 'a b c' ~~ / a b c /; # OUTPUT: «False» 1887 1888# NOTE: Please use quotes or `:s` (`:sigspace`) modifier (or, to suppress this 1889# warning, omit the space, or otherwise change the spacing). To fix this and make 1890# the spaces less ambiguous, either use at least two spaces between strings 1891# or use the `:s` adverb. 1892 1893# As we saw before, we can embed the `:s` inside the slash delimiters, but we 1894# can also put it outside of them if we specify `m` for 'match': 1895say so 'a b c' ~~ m:s/a b c/; # OUTPUT: «True␤» 1896 1897# By using `m` to specify 'match', we can also use other delimiters: 1898say so 'abc' ~~ m{a b c}; # OUTPUT: «True␤» 1899say so 'abc' ~~ m[a b c]; # OUTPUT: «True␤» 1900 1901# `m/.../` is equivalent to `/.../`: 1902say 'raku' ~~ m/raku/; # OUTPUT: «True␤» 1903say 'raku' ~~ /raku/; # OUTPUT: «True␤» 1904 1905# Use the `:i` adverb to specify case insensitivity: 1906say so 'ABC' ~~ m:i{a b c}; # OUTPUT: «True␤» 1907 1908# However, whitespace is important as for how modifiers are applied 1909# (which you'll see just below) ... 1910 1911# 1912# 18.1 Quantifiers - `?`, `+`, `*` and `**`. 1913# 1914 1915# `?` - zero or one match 1916say so 'ac' ~~ / a b c /; # OUTPUT: «False␤» 1917say so 'ac' ~~ / a b? c /; # OUTPUT: «True␤», the "b" matched 0 times. 1918say so 'abc' ~~ / a b? c /; # OUTPUT: «True␤», the "b" matched 1 time. 1919 1920# ... As you read before, whitespace is important because it determines which 1921# part of the regex is the target of the modifier: 1922say so 'def' ~~ / a b c? /; # OUTPUT: «False␤», only the "c" is optional 1923say so 'def' ~~ / a b? c /; # OUTPUT: «False␤», whitespace is not significant 1924say so 'def' ~~ / 'abc'? /; # OUTPUT: «True␤», the whole "abc" group is optional 1925 1926# Here (and below) the quantifier applies only to the "b" 1927 1928# `+` - one or more matches 1929say so 'ac' ~~ / a b+ c /; # OUTPUT: «False␤», `+` wants at least one 'b' 1930say so 'abc' ~~ / a b+ c /; # OUTPUT: «True␤», one is enough 1931say so 'abbbbc' ~~ / a b+ c /; # OUTPUT: «True␤», matched 4 "b"s 1932 1933# `*` - zero or more matches 1934say so 'ac' ~~ / a b* c /; # OUTPUT: «True␤», they're all optional 1935say so 'abc' ~~ / a b* c /; # OUTPUT: «True␤» 1936say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «True␤» 1937say so 'aec' ~~ / a b* c /; # OUTPUT: «False␤», "b"(s) are optional, not replaceable. 1938 1939# `**` - (Unbound) Quantifier 1940# If you squint hard enough, you might understand why exponentiation is used 1941# for quantity. 1942say so 'abc' ~~ / a b**1 c /; # OUTPUT: «True␤», exactly one time 1943say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «True␤», one to three times 1944say so 'abbbc' ~~ / a b**1..3 c /; # OUTPUT: «True␤» 1945say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPUT: «Fals␤», too much 1946say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPUT: «True␤», infinite ranges are ok 1947 1948# 1949# 18.2 `<[]>` - Character classes 1950# 1951 1952# Character classes are the equivalent of PCRE's `[]` classes, but they use a 1953# more raku-ish syntax: 1954say 'fooa' ~~ / f <[ o a ]>+ /; # OUTPUT: «fooa␤» 1955 1956# You can use ranges (`..`): 1957say 'aeiou' ~~ / a <[ e..w ]> /; # OUTPUT: «ae␤» 1958 1959# Just like in normal regexes, if you want to use a special character, escape 1960# it (the last one is escaping a space which would be equivalent to using 1961# ' '): 1962say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; # OUTPUT: «he-he !␤» 1963 1964# You'll get a warning if you put duplicate names (which has the nice effect 1965# of catching the raw quoting): 1966'he he' ~~ / <[ h e ' ' ]> /; 1967# Warns "Repeated character (') unexpectedly found in character class" 1968 1969# You can also negate character classes... (`<-[]>` equivalent to `[^]` in PCRE) 1970say so 'foo' ~~ / <-[ f o ]> + /; # OUTPUT: «False␤» 1971 1972# ... and compose them: 1973# any letter except "f" and "o" 1974say so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # OUTPUT: «False␤» 1975 1976# no letter except "f" and "o" 1977say so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # OUTPUT: «True␤» 1978 1979# the + doesn't replace the left part 1980say so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # OUTPUT: «True␤» 1981 1982# 1983# 18.3 Grouping and capturing 1984# 1985 1986# Group: you can group parts of your regexp with `[]`. Unlike PCRE's `(?:)`, 1987# these groups are *not* captured. 1988say so 'abc' ~~ / a [ b ] c /; # OUTPUT: «True␤», the grouping does nothing 1989say so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /; # OUTPUT: «True␤» 1990 1991# The previous line returns `True`. The regex matches "012" one or more time 1992# (achieved by the the `+` applied to the group). 1993 1994# But this does not go far enough, because we can't actually get back what 1995# we matched. 1996 1997# Capture: The results of a regexp can be *captured* by using parentheses. 1998say so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # OUTPUT: «True␤» 1999# (using `so` here, see `$/` below) 2000 2001# So, starting with the grouping explanations. As we said before, our `Match` 2002# object is stored inside the `$/` variable: 2003say $/; # Will either print the matched object or `Nil` if nothing matched. 2004 2005# As we also said before, it has array indexing: 2006say $/[0]; # OUTPUT: «「ABC」 「ABC」␤», 2007 2008# The corner brackets (「..」) represent (and are) `Match` objects. In the 2009# previous example, we have an array of them. 2010 2011say $0; # The same as above. 2012 2013# Our capture is `$0` because it's the first and only one capture in the 2014# regexp. You might be wondering why it's an array, and the answer is simple: 2015# Some captures (indexed using `$0`, `$/[0]` or a named one) will be an array 2016# if and only if they can have more than one element. Thus any capture with 2017# `*`, `+` and `**` (whatever the operands), but not with `?`. 2018# Let's use examples to see that: 2019 2020# NOTE: We quoted A B C to demonstrate that the whitespace between them isn't 2021# significant. If we want the whitespace to *be* significant there, we can use the 2022# `:sigspace` modifier. 2023say so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # OUTPUT: «True␤» 2024say $/[0]; # OUTPUT: «「ABC」␤» 2025say $0.WHAT; # OUTPUT: «(Match)␤» 2026 # There can't be more than one, so it's only a single match object. 2027 2028say so 'foobar' ~~ / foo ( "A" "B" "C" )? bar /; # OUTPUT: «True␤» 2029say $0.WHAT; # OUTPUT: «(Any)␤», this capture did not match, so it's empty. 2030 2031say so 'foobar' ~~ / foo ( "A" "B" "C" ) ** 0..1 bar /; #=> OUTPUT: «True␤» 2032say $0.WHAT; # OUTPUT: «(Array)␤», A specific quantifier will always capture 2033 # an Array, be a range or a specific value (even 1). 2034 2035# The captures are indexed per nesting. This means a group in a group will be 2036# nested under its parent group: `$/[0][0]`, for this code: 2037'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /; 2038say $/[0].Str; # OUTPUT: «hello~␤» 2039say $/[0][0].Str; # OUTPUT: «~␤» 2040 2041# This stems from a very simple fact: `$/` does not contain strings, integers 2042# or arrays, it only contains `Match` objects. These contain the `.list`, `.hash` 2043# and `.Str` methods but you can also just use `match<key>` for hash access 2044# and `match[idx]` for array access. 2045 2046# In the following example, we can see `$_` is a list of `Match` objects. 2047# Each of them contain a wealth of information: where the match started/ended, 2048# the "ast" (see actions later), etc. You'll see named capture below with 2049# grammars. 2050say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list␤» 2051 2052# Alternation - the `or` of regexes 2053# WARNING: They are DIFFERENT from PCRE regexps. 2054say so 'abc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Either "b" or "y". 2055say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Obviously enough... 2056 2057# The difference between this `|` and the one you're used to is 2058# LTM ("Longest Token Matching") strategy. This means that the engine will 2059# always try to match as much as possible in the string. 2060say 'foo' ~~ / fo | foo /; # OUTPUT: «foo», instead of `fo`, because it's longer. 2061 2062# To decide which part is the "longest", it first splits the regex in two parts: 2063# 2064# * The "declarative prefix" (the part that can be statically analyzed) 2065# which includes alternations (`|`), conjunctions (`&`), sub-rule calls (not 2066# yet introduced), literals, characters classes and quantifiers. 2067# 2068# * The "procedural part" includes everything else: back-references, 2069# code assertions, and other things that can't traditionally be represented 2070# by normal regexps. 2071 2072# Then, all the alternatives are tried at once, and the longest wins. 2073 2074# Examples: 2075# DECLARATIVE | PROCEDURAL 2076/ 'foo' \d+ [ <subrule1> || <subrule2> ] /; 2077 2078# DECLARATIVE (nested groups are not a problem) 2079/ \s* [ \w & b ] [ c | d ] /; 2080 2081# However, closures and recursion (of named regexes) are procedural. 2082# There are also more complicated rules, like specificity (literals win 2083# over character classes). 2084 2085# NOTE: The alternation in which all the branches are tried in order 2086# until the first one matches still exists, but is now spelled `||`. 2087say 'foo' ~~ / fo || foo /; # OUTPUT: «fo␤», in this case. 2088 2089#################################################### 2090# 19. Extra: the MAIN subroutine 2091#################################################### 2092 2093# The `MAIN` subroutine is called when you run a Raku file directly. It's 2094# very powerful, because Raku actually parses the arguments and pass them 2095# as such to the sub. It also handles named argument (`--foo`) and will even 2096# go as far as to autogenerate a `--help` flag. 2097 2098sub MAIN($name) { 2099 say "Hello, $name!"; 2100} 2101# Supposing the code above is in file named cli.raku, then running in the command 2102# line (e.g., $ raku cli.raku) produces: 2103# Usage: 2104# cli.raku <name> 2105 2106# And since MAIN is a regular Raku sub, you can have multi-dispatch: 2107# (using a `Bool` for the named argument so that we can do `--replace` 2108# instead of `--replace=1`. The presence of `--replace` indicates truthness 2109# while its absence falseness). For example: 2110 2111 # convert to IO object to check the file exists 2112 =begin comment 2113 subset File of Str where *.IO.d; 2114 2115 multi MAIN('add', $key, $value, Bool :$replace) { ... } 2116 multi MAIN('remove', $key) { ... } 2117 multi MAIN('import', File, Str :$as) { ... } # omitting parameter name 2118 =end comment 2119 2120# Thus $ raku cli.raku produces: 2121# Usage: 2122# cli.raku [--replace] add <key> <value> 2123# cli.raku remove <key> 2124# cli.raku [--as=<Str>] import <File> 2125 2126# As you can see, this is *very* powerful. It even went as far as to show inline 2127# the constants (the type is only displayed if the argument is `$`/is named). 2128 2129#################################################### 2130# 20. APPENDIX A: 2131#################################################### 2132 2133# It's assumed by now you know the Raku basics. This section is just here to 2134# list some common operations, but which are not in the "main part" of the 2135# tutorial to avoid bloating it up. 2136 2137# 2138# 20.1 Operators 2139# 2140 2141# Sort comparison - they return one value of the `Order` enum: `Less`, `Same` 2142# and `More` (which numerify to -1, 0 or +1 respectively). 2143say 1 <=> 4; # OUTPUT: «More␤», sort comparison for numerics 2144say 'a' leg 'b'; # OUTPUT: «Lessre␤», sort comparison for string 2145say 1 eqv 1; # OUTPUT: «Truere␤», sort comparison using eqv semantics 2146say 1 eqv 1.0; # OUTPUT: «False␤» 2147 2148# Generic ordering 2149say 3 before 4; # OUTPUT: «True␤» 2150say 'b' after 'a'; # OUTPUT: «True␤» 2151 2152# Short-circuit default operator - similar to `or` and `||`, but instead 2153# returns the first *defined* value: 2154say Any // Nil // 0 // 5; # OUTPUT: «0␤» 2155 2156# Short-circuit exclusive or (XOR) - returns `True` if one (and only one) of 2157# its arguments is true 2158say True ^^ False; # OUTPUT: «True␤» 2159 2160# Flip flops. These operators (`ff` and `fff`, equivalent to P5's `..` 2161# and `...`) are operators that take two predicates to test: They are `False` 2162# until their left side returns `True`, then are `True` until their right 2163# side returns `True`. Similar to ranges, you can exclude the iteration when 2164# it become `True`/`False` by using `^` on either side. Let's start with an 2165# example : 2166 2167for <well met young hero we shall meet later> { 2168 # by default, `ff`/`fff` smart-match (`~~`) against `$_`: 2169 if 'met' ^ff 'meet' { # Won't enter the if for "met" 2170 .say # (explained in details below). 2171 } 2172 2173 if rand == 0 ff rand == 1 { # compare variables other than `$_` 2174 say "This ... probably will never run ..."; 2175 } 2176} 2177 2178# This will print "young hero we shall meet" (excluding "met"): the flip-flop 2179# will start returning `True` when it first encounters "met" (but will still 2180# return `False` for "met" itself, due to the leading `^` on `ff`), until it 2181# sees "meet", which is when it'll start returning `False`. 2182 2183# The difference between `ff` (awk-style) and `fff` (sed-style) is that `ff` 2184# will test its right side right when its left side changes to `True`, and can 2185# get back to `False` right away (*except* it'll be `True` for the iteration 2186# that matched) while `fff` will wait for the next iteration to try its right 2187# side, once its left side changed: 2188 2189# The output is due to the right-hand-side being tested directly (and returning 2190# `True`). "B"s are printed since it matched that time (it just went back to 2191# `False` right away). 2192.say if 'B' ff 'B' for <A B C B A>; # OUTPUT: «B B␤», 2193 2194# In this case the right-hand-side wasn't tested until `$_` became "C" 2195# (and thus did not match instantly). 2196.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤», 2197 2198# A flip-flop can change state as many times as needed: 2199for <test start print it stop not printing start print again stop not anymore> { 2200 # exclude both "start" and "stop", 2201 .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # OUTPUT: «print it print again␤» 2202} 2203 2204# You might also use a Whatever Star, which is equivalent to `True` for the 2205# left side or `False` for the right, as shown in this example. 2206# NOTE: the parenthesis are superfluous here (sometimes called "superstitious 2207# parentheses"). Once the flip-flop reaches a number greater than 50, it'll 2208# never go back to `False`. 2209for (1, 3, 60, 3, 40, 60) { 2210 .say if $_ > 50 ff *; # OUTPUT: «60␤3␤40␤60␤» 2211} 2212 2213# You can also use this property to create an `if` that'll not go through the 2214# first time. In this case, the flip-flop is `True` and never goes back to 2215# `False`, but the `^` makes it *not run* on the first iteration 2216for <a b c> { .say if * ^ff *; } # OUTPUT: «b␤c␤» 2217 2218# The `===` operator, which uses `.WHICH` on the objects to be compared, is 2219# the value identity operator whereas the `=:=` operator, which uses `VAR()` on 2220# the objects to compare them, is the container identity operator.

If you want to go further and learn more about Raku, you can:

  • Read the Raku Docs. This is a great resource on Raku. If you are looking for something, use the search bar. This will give you a dropdown menu of all the pages referencing your search term (Much better than using Google to find Raku documents!).

  • Read the Raku Advent Calendar. This is a great source of Raku snippets and explanations. If the docs don’t describe something well enough, you may find more detailed information here. This information may be a bit older but there are many great examples and explanations.

  • Come along on #raku at irc.libera.chat. The folks here are always helpful.

  • Check the source of Raku’s functions and classes. Rakudo is mainly written in Raku (with a lot of NQP, «Not Quite Perl», a Raku subset easier to implement and optimize).

  • Read the language design documents. They explain Raku from an implementor point-of-view, but it’s still very interesting.