Raku By Example
View me onGitHub
## ^ twigil 为block 块 或 子例程 申明了一个形式位置参数. 
## 形如 $^variable 的变量是一种占位变量. 它们可用在裸代码块中来申明代码块的形式参数. 看下面代码中的块: 

for ^4 {
    say "$^seconds follows $^first";
}

## 1 follows 0
## 3 follows 2


## dot twigil
 class Point {
        has $.x;
        has $.y;

        method Str() {
           return ($.x, $.y); # 注意我们这次使用 . 而不是 !
        }
    }

my $p = Point.new(x=>10,y=>20);
my ($height,$wide) = $p.Str();
say "高度:$height";
say "宽度:$wide";


 class SaySomething {
        method a() { say "a"; }
        method b() { say $.a; }
    }

    SaySomething.a; # prints "a"
    SaySomething.b;


## pointy block
my @fave_foods = <hanbao pingguo TV>;
for @fave_foods -> $food {
    say "Jonathan likes to eat $food";
}
# The bit between the curly braces is done for each thing in the array
# -> $name means “declare $name and put the current thing into it”

# $^identifier 变量用于块中:

my @str = <a very long but shorthand really>;
my @sorted = sort { $^a.chars <=> $^b.chars}, @str;
say @sorted;

# sort 可以更简洁
my @s = sort { .chars }, @str;
say @s;

my $block = {
    $^a + $^b;
};
say $block(1,99);

## Twigils影响变量的作用域。请记住, twigils 对基本的魔符插值没有影响,那就是:
## 如果  $a 内插, $^a, $*a, $=a, $?a, $.a, 等等也会内插. 它仅仅取决于 $.

my $lexical   = 1;
my $*dynamic1 = 10;
my $*dynamic2 = 100;

sub say-all() {
    say "$lexical, $*dynamic1, $*dynamic2";
}

# prints 1, 10, 100
say-all();

{
    my $lexical   = 2;
    my $*dynamic1 = 11;
    $*dynamic2    = 101;
    # prints 1, 11, 101 ,why 2, 11 ,101?
    # $lexical isn't looked up in the caller's scope but in the scope &say-all was defined in.
    # The two dynamic variables are looked up in the callers scope and therefore have the values 11 and 101.
    # 翻译过来就是, $lexical 不是在调用者的作用域内被查找, 而是在 &say-all 被定义的作用域那儿
    # 也就是第一行的 $lexical = 1 了. 另外两个动态作用域变量在调用者的作用域内被查找, 所以值为 11 和 101 
    say-all();
}

# prints 1, 10, 101
say-all();

## ? twigil 编译常量
say "$?FILE: $?LINE"; # wenhao.p6: 4