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

<<Previous: say q:2 '@*Examples.[4] &Perl6()';  >>Next: multi sub Examples (6, Perl6) {...}

sub Perl6 (*@Examples[5] is copy)

Category: Perl6   Keywords: Perl6 sub

Bubble

以前在 @Examples[0] is Perl6 里一开始就稍微讲了点子程序,而在 my Perl6 @Examples[3] 中也讲了子程序参数和返回类型。
现在接着讲 sub/子程序

Perl 5 的代码在 Perl 6 中会怎么样?

虽然说 Perl 5 这样的代码在 Perl 6 中也是可行的:
sub say { print qq{"@_"\n}; }
但要注意一点,这里的 @_ 是只读的。下面的代码会出错:
sub cap { $_ = uc $_ for @_ }   # Error: elements of @_ are constant
如果你想要更新 @_, 用 is rw 来指定。
sub swap (*@_ is rw) { @_[0,1] = @_[1,0] }
而预先声明却不定义一个子程序,Perl 5 中可以这么写:
sub foo;
这在 Perl 6 中会报错,Perl 6 必须得这么写:(那三个点是语法的一部分。)
sub foo {...}

如何定义一个全局子程序

我们在 say q:2 '@*Examples.[4] &Perl6()'; 中说用 * 来声明一个真正的全局变量,而子程序也一样:
# from S06.pod
    $*next_id = 0; # 全局变量
    sub *saith($text)  { print "Yea verily, $text" } # 全局子程序

    module A {
        my $next_id = 2;    # hides any global or package $next_id / 隐藏任何全局或包变量 $next_id
        saith($next_id);    # print the lexical $next_id; / 输出词汇变量 $next_id,这里为 2
        saith($*next_id);   # print the global $next_id; / 输出全局变量 $next_id, 这里为 0
    }

    module B {
        saith($next_id);    # Unambiguously the global $next_id / 显然是全局变量 $next_id,这里为 0
    }

参数分配

is rw/is copy

OUTER::

如果你在子程序里定义了 $x, 又想获得子程序外面的 $x 的话,可以使用 OUTER::
{ my $a = 1; {
   my $a=2; {
      my $a=3;
      say $a; # 3
      say $OUTER::a; # 2
      say $OUTER::OUTER::a; # 1
}}}

want

在 Perl 5 中如果区别返回值是数组和标量时我们用 wantarray, 在 Perl 6 中将不再有这东西,而用更强大的 want 来代替。例子:
given want { 
   when Scalar {...} # 返回一个标量 
   when List   {...} # 要一个列表
   when 2      {...} # 要两个值
}

Correct me when I'm wrong

Exercise more.

<<Previous: say q:2 '@*Examples.[4] &Perl6()';  >>Next: multi sub Examples (6, Perl6) {...}

Options: +Del.icio.us

Related items Created on 2005-05-22 15:37:26, Last modified on 2005-05-24 23:45:37
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.