我知道Swift有命名元组:
let twostraws = (name: "twostraws", password: "fr0st1es")
因此,我可以说:
print(twostraws.name) # twostraws
但在Perl 6中,我会这样说:
my $list = (twostraws, fr0st1es);
say $list[0];
Perl 6中是否有命名元组?但这并不像Swift那样棒,请注意。
我知道Swift有命名元组:
let twostraws = (name: "twostraws", password: "fr0st1es")
因此,我可以说:
print(twostraws.name) # twostraws
但在Perl 6中,我会这样说:
my $list = (twostraws, fr0st1es);
say $list[0];
有多种方法可以获得类似的东西。
简单哈希(推荐)
my \twostraws = %( 'name' => 'twostraws', 'password' => 'fr0st1es' );
print twostraws<name>; # twostraws{ qw'name' }
包含两种方法的列表
my \twostraws = ( 'twostraws', 'fr0st1es' ) but role {
method name () { self[0] }
method password () { self[1] }
}
put twostraws.name; # `put` is like `print` except it adds a newline
匿名类
my \twostraws = class :: {
has ($.name, $.password)
}.new( :name('twostraws'), :password('fr0st1es') )
say twostraws.name; # `say` is like `put` but calls the `.gist` method
可能还有一些我还没想到的。真正的问题是你将如何在代码的其余部分中使用它。
sub circumfix:<\
`> ( @ ($name,$password)) { %( :$name, :$password ) }; say ` 'twostraws', 'fr0st1es' `<name>` - Brad Gilbert枚举可以有不是 Int 类型的值类型。您可以将它们声明为 Pair 列表。
enum Twostraws (name => "twostraws", password => "fr0st1es");
say name; # OUTPUT«twostraws»
say password; # OUTPUT«fr0st1es»
say name ~~ Twostraws, password ~~ Twostraws; # OUTPUT«TrueTrue»
say name.key, ' ', name.value; # OUTPUT«name twostraws»
enum
声明的类型可以像其他类型一样使用。sub picky(Twostraws $p){ dd $p };
picky(password); # OUTPUT«Twostraws::password»
编辑:请查看https://github.com/perl6/roast/blob/master/S12-enums/non-int.t
该链接指向的网站包含与非整数枚举相关的测试代码。Perl6 中的等价类型是 Pair 类型,其构造运算符为 =>。它们是不可变的——一旦创建了键和值,就不能更改。
$ perl6
> my $destination = "Name" => "Sydney" ;
Name => Sydney
> say $destination.WHAT ;
(Pair)
> $destination.value = "London";
Cannot modify an immutable Str
in block <unit> at <unknown file> line 1
>
与perl5中的“fat comma”类似,如果左侧是单个标识符,则构造函数不需要将其引用。还有一种称为“冒号对”的表达键值对的替代语法。您可以将多个Pairs收集到列表中,但它们只能按位置访问。
> $destination = ( Name => "Sydney" , :Direction("East") , :Miles(420) );
(Name => Sydney Direction => East Miles => 420)
> say $destination.WHAT ;
(List)
> say $destination[1] ;
Direction => East
>
冒号对语法有方便的变体 - 如果值是字符串,您可以用尖括号替换括号并去掉引号。如果值是整数,您可以在值后立即列出键,无需引号。如果值为布尔值,则如果值为True,则可以仅列出键,否则在值前加上 !
。
最后,您可以将其中一些分配到哈希中,在哈希中可以通过键访问值,并且这些值是可变的。
> my %destination = ( :Name<Sydney> , :Direction<East> , :420miles , :!visited ) ;
Direction => East, Name => Sydney, miles => 420, visited => False
> say %destination<miles> ;
420
> %destination<visited> = True ;
True
>
say $list[0].WHAT;
来查看类型。 - zb226