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

<<Previous: given @Examples[1] when Perl6  >>Next: Share the URLs with u (May 2005)

@Perl6 <== @Examples xx 2

Category: Perl6   Keywords: Operators Perl6

本文介绍了一些新的操作符,未完成。

~, ??::, //, x, xx, ==>, <==, :, :=, ::=, =:=, »«, >><<

  1. ~ 将它的参数强制为字符串上下文,+ 强制为数字上下文,? 强制为布尔型上下文,* 为列表上下文。
    +@foo        # @foo.elems 获得数组的个数
    ~@foo        # join ' ', @foo
    ?@foo        # ? @foo.elems
    +%foo        # +%foo.keys
  2. 条件操作符由原来的 ?: 变为 ??::
  3. 操作符 // 与 || 不同的是查看左侧的是否定义(即使为假也没事),而 || 查看是否为真。
  4. xxx, x 操作 scalar, xx 操作 array
    my $twin = "Lintilla";
    $twin x= 2;          # "LintillaLintilla"
    
    @array = "Lintilla" xx 3; # ("Lintilla", "Lintilla", "Lintilla")
    
    @array = (4, 2);
    @array xx= 2;              # now (4, 2, 4, 2)
  5. 新操作符 ==><== 它作用于参数和返回值都是列表的函数。以前用 map grep 写很长的代码,要从右往左看比较别扭。用这两操作符可以看起来比较清晰。
    # Perl 5
    @result = map { floor($^x / 2) } grep { /^ \d+ $/ } @data;
    # Perl 6
    @data ==> grep { /^ \d+ $/ }
          ==> map { floor($^x / 2) }
          ==> @result;
    # or
    @result <== map { floor($^x / 2) }
            <== grep { /^ \d+ $/ }
            <== @data;
  6. : 的意思:
    feed $hacker: 'Pizza and cola'; # 等同于 $hacker.feed('Pizza and cola');
  7. :=, ::=, =:=. := 称为绑定,我们将不再有 typeglob 类型,而用 := 来代替。::= 与 := 做相同的事情,不同的是 ::= 是运行在编译时。=:= 用以比较两个变量是否绑定。
    my $x = 'Just Another';
    my $y := $x;
    $y = 'Perl Hacker'; # $x 和 $y 都变为 'Perl Hacker'
    
    print '$x is the same as $y' if $x =:= $y; # true
    
    my $z := $y;
    print '$x is the same as $y' if $x =:= $z; # true
    
  8. 我们管这种操作符 »«, >><< 为向量操作符。它对数组操作并返回数组。每一个操作符(包括你自己定义的)都有对应的向量操作符。因为它默认的上下文是数组,所以当一边是标量时会将标量扩充为数组。例子:
    print join('-', (1,1,2,3,5) »+« (1,2,3,5,1)); # 2-3-5-8-6
    print join('-', (1,4,2,3,5) >>-<< 1); # 右边为标量扩充为 (1,1,1,1,1), 结果为 0-3-1-2-4
    print join('-', (1,4,2,3,5) »-« (1,1)); # 目前 pugs 是将右边补齐为 (1,1,undef,undef,undef), 结果为 0-3-2-3-5
    我们不仅有二元向量操作符,还有一元的(左操作符加«,»加右操作符):
    @negatives = -« @positives; # 所有元素前加负号
    @a »++; # 每个元素加 1
    ("f","oo","bar")».length;   # (1,2,3)
    @objects ».run(); # 每个 @objects 元素都执行 run()
    方法调用为 postfix, 不是 infix, 所以是加 ». 后面没有 «
    因为在 ASCII 下不能输出 »«, 所以我们用 >><<来代替。

Correction is welcomed

God bless us.

<<Previous: given @Examples[1] when Perl6  >>Next: Share the URLs with u (May 2005)

Options: +Del.icio.us

Related items Created on 2005-05-20 18:53:54, Last modified on 2005-05-24 17:49:52
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.