能否在Raku语言的map块中使用数组索引?
Raku中在map例程里获取数组索引的方法
当然可以,Raku提供了几种简洁的方式实现这个需求,以下是常用方法:
使用
.kv方法.kv会返回数组的索引与对应元素的键值对序列,你可以在map中按顺序捕获索引和元素:raku -e 'my @a = "First", "Second", "Third", "First"; say @a.kv.map({ "Index of $^value is: $^key;" })'这里
$^key会捕获索引,$^value捕获元素值,执行后就能得到你想要的输出。你也可以用显式的解构写法让逻辑更清晰:raku -e 'my @a = "First", "Second", "Third", "First"; say @a.kv.map(-> ($index, $item) { "Index of $item is: $index;" })'使用
.pairs方法.pairs返回包含Pair对象的序列,每个Pair的.key属性对应索引,.value属性对应元素:raku -e 'my @a = "First", "Second", "Third", "First"; say @a.pairs.map({ "Index of $_.value is: $_.key;" })'
两种方法执行后都会输出:
(Index of First is: 0; Index of Second is: 1; Index of Third is: 2; Index of First is: 3;)
内容的提问来源于stack exchange,提问作者Mimosinnet
相关产品推荐
相关产品推荐

