Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: Synopsis localization  >>Next: given @Examples[1] when Perl6

@Examples[0] is Perl6

Category: Perl6   Keywords: Perl6

想写点 Perl 6 的东西,却不知道从哪写起,只好写一步算一步了。

子程序参数传递

在 Perl 5 中一般来说都用如下代码获得子程序的参数:
sub foo {
    my ($a, $b) = @_; # or my $self = shift;
在 Perl 6 中

for 循环语句

foreach 将不再被使用。 Perl 6 中 for 语句一般这么写:
for @foo {...}
这跟 Perl 5 中没有区别。另一种为:
for @foo -> $item { print $item }
-> 这种写法是种很强大的写法。
  1. 一次取多个变量,例如:
    my @foo = (1,2,3);
    for @foo -> $item1, $item2 {
        print $item1, $item2, '-';输出为 12-3-
    }
  2. 历遍一个 Hash 的写法:(%hash.kv 是将 %hash 变为一个列表,($key1, $value1, $key2, $value2, ...)
    for %hash.kv -> $key, $value { print "$key => $value\n" }
  3. 多个数组写法:(这在 Perl 5 中要用两个 for 才行)
    for zip(@a;@b) -> $a, $b { print "[$a, $b]\n" }
    # or for @a ¥ @b ¥ @c -> $a, $b, $c { print "[$a, $b, $c]\n" }
    
    ¥ 是 zip 的操作符。

最后值得注意的是

for @foo -> $item { print $item }
这种写法里 $item 是只读的,不是可写的。如果想要在块里改变 $item 的值,必须在后面加上 is rw (rw 是可读写 readwrite 的缩写)
my @foo = (1,2,3);
for @foo -> $item is rw {
    $item ~= 'a'; # 连接字符串以前用 $a . $b, 现在要用 $a ~ $b 了
    print $item;
}
而 for @foo { ... } 中 $_ 默认为可读写,也就是说它等同于 for @foo -> $_ is rw { ... }

Correct me if I'm wrong

Enjoy!

<<Previous: Synopsis localization  >>Next: given @Examples[1] when Perl6

Options: +Del.icio.us

Related items Created on 2005-05-19 20:26:08, Last modified on 2005-05-25 20:18:22
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.