当前位置: 首页 > 文档资料 > Perl6 入门指导 >

第三章 Perl6 中的联结

优质
小牛编辑
128浏览
2023-12-01

联结

在前面的章节中,我们已经见识过如何使用联结来检查某一个值是否存在于给定的一组数据中。

译注:

类型构造符运算符返回为真时的条件
allall&计算后所有值均Ture
anyany|计算后至少有一个值为Ture
oneone^计算后有且仅有一个值为True
nonenone计算后所有值均为False

详情请见Junction

tutorial/junctions/intro.p6

#!/usr/bin/env perl6
use v6;

my $possible_options = 1|2|3;
my $c = prompt "please give a number(1,2 or 3): ";
if $c == $possible_options {
    say "Correct choice: $c";
} else {
    say "Incorrect choice: $c";
}

更多关于联结的练习

tutorial/junctions/operators.p6

#!/usr/bin/env perl6
use v6;

my $options = 1|2|3;

$options *= 2;    # 现在联结中的值为 2|4|6

for 1..8 -> $i {
    if $i == $options {
        say $i;
    }
}

tutorial/junctions/substr.p6

#!/usr/bin/env perl6
use v6;

my $x = 0|6;
my $str = "Hello World";
my $sub = substr($str, $x, 5);

#my @values = $sub.values;
#say @values;
#say "{@values}";        # Hello World
#say $sub.values[0];     # Hello
#say $sub.values.elems;  # 2 - 联结中元素的个数

tutorial/junctions/j.p6

#!/usr/bin/env perl6
use v6;

my $x = 1|2;                            # 联结
if $x == 1 { say 't' } else { say 'f' } # t
if $x == 2 { say 't' } else { say 'f' } # t
if $x == 3 { say 't' } else { say 'f' } # f 
if $x != 1 { say 't' } else { say 'f' } # f 结果与 $x != 2 相同
if !($x == 1) { say 't' } else { say 'f' } # f

#TODO
#my @values = $x.values;          # 以随机顺序获取联结中的值
#say $x.values.elems;             # 2  
#say $x.values[0] + $x.values[1]; # 3
#
#my $y = 1|1|2;
#say $y.values.elems;             # 2
#say $y.values[0] + $y.values[1]; # 3
## 1|1|2    和 1|2 相同
#
#my $r1 = (1|2 == 1);  # (Bool::False | Bool::True)
#my $r2 = (1|2 == 2);  # (Bool::False | Bool::True)
#
#my $r3 = (1|2 == 3);  # (Bool::False)
#                      # 这里只会返回一个元素,因为多个相同的布尔值是没有意义的
#                      # 这里归约的规则与 1|1|2 大致相同
#

tutorial/junctions/x.p6

#!/usr/bin/env perl6
use v6;

#my $x = any(1,2,3);
#my $z = any(1);
#say $x - $z;

my @numbers = (1, 2, 3);
my @new = (5, 3);
if (all(@new) > all(@numbers)) {
    say "all bigger";
}

if (any(@new) > all(@numbers)) {
    say "there is at least one bigger";
}

#my $diff = all(@numbers) and none(@new);
#say $diff.perl;

tutorial/junctions/any.p6

#!/usr/bin/env perl6
use v6;

my @names = <Foo Bar Moo>;
my $username = prompt "Please type in your name: ";
if $username eq any(@names) {
    say "Welcome $username";
} else {
    say "Unknown user $username";
}

#if ($username eq any(@names)) {
#    say "Welcome $username";
#}