我知道Swift已经命名了元组:
let twostraws = (name: "twostraws", password: "fr0st1es")
所以我可以说:
print(twostraws.name) # twostraws
但在Perl 6中我会说:
my $list = (twostraws, fr0st1es);
say $list[0];
哪个不像Swift那么棒,所以我想知道Perl 6中是否有命名元组?
答案 0 :(得分:10)
有各种方法可以获得类似的东西。
简单哈希(推荐)
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
我可能还有很多其他想法。真正的问题是如何在代码的其余部分中使用它。
答案 1 :(得分:5)
Enums can have value types that are not Int. You declare them as a list of Pairs.
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»
The type that is declared with enum
can be used just like any other type.
sub picky(Twostraws $p){ dd $p };
picky(password); # OUTPUT«Twostraws::password»
Edit: see https://github.com/perl6/roast/blob/master/S12-enums/non-int.t中使用php和文字
答案 2 :(得分:4)
看起来你正在寻找的Perl 6中的类型是一个哈希值。
参见相关文件:
这是一个Perl 6示例,应该等同于您的Swift示例:
my %twostraws = name => 'twostraws', password => 'fr0st1es';
print %twostraws<name>; # twostraws
答案 3 :(得分:3)
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
>
喜欢&#34;胖子逗号&#34;从perl5开始,如果构造函数是单个标识符,则它不需要引用左侧。有一种表达Pairs的替代语法称为&#34;冒号对&#34;。您可以将多个Pairs togeather收集到一个列表中,但它们只能在位置上访问;
> $destination = ( Name => "Sydney" , :Direction("East") , :Miles(420) );
(Name => Sydney Direction => East Miles => 420)
> say $destination.WHAT ;
(List)
> say $destination[1] ;
Direction => East
>
冒号对语法有一些方便的变体 - 如果值是一个字符串,您可以用尖括号替换括号并删除引号。如果该值是整数,则可以在之后立即列出该键,而不带引号。如果值为boolean,则可以在值为True时单独列出密钥,如果值为False,则可以使用!
作为前缀。
最后,您可以将其中的一些分配到散列中,其中值可以通过键访问并且是可变的;
> my %destination = ( :Name<Sydney> , :Direction<East> , :420miles , :!visited ) ;
Direction => East, Name => Sydney, miles => 420, visited => False
> say %destination<miles> ;
420
> %destination<visited> = True ;
True
>