在 Raku 中一步使用一个变量并为其分配一个表达式
Use a variable and assign an expression to it in one step in Raku
我正在尝试使用一个变量并在一步中为其分配一个表达式:
给定的(示例)代码
my @l=<a b c d e f g h i j k>;
my $i=0;
while $i < 7 {
say @l[$i];
$i= ($i+1) * 2;
}
# Output:
# a
# c
# g
所需功能:
my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[$i =~ ($i+1) * 2] while $i < 7;
# Here, first the @l[$i] must be evaluated
# then $i must be assigned to the expression
# ($i+1) * 2
# (The =~ operator is selected just as an example)
# Output:
# The same output as above should come, that is:
# a
# c
# g
在使用变量 $i
之后,(示例)表达式 ($i+1) * 2
应该在一步中分配给它,并且应该 仅在数组索引 @l[$i =~ ($i+1) * 2]
即 while
的参数应该 而不是 被改变。
这里我以 Regex 方程运算符 =~
(检查和赋值运算符,AFAIK)为例。当然,在这种情况下,它是行不通的。
我需要 是否有任何操作员或一些解决方法来实现该功能?谢谢。
你是说,像这样的东西?
my @l = <a b c d e f g h i j k>;
say @l[ 0, (* + 1) * 2 ...^ * > 7 ]; # says a c g;
有点冗长:
my @l = <a b c d e f g h i j k>;
say @l[ 0, -> $i { ($i + 1) * 2 } ...^ -> $i { $i > 7 } ];
甚至
my sub next-i( $i ) { ($i + 1) * 2 };
my sub last-i( $i ) { $i > 7 };
my @l = <a b c d e f g h i j k>;
say @l[ 0, &next-i ...^ &last-i ];
编辑:或者,如果在下面的评论中你事先知道元素的数量,你可以去掉结束块并(简化?)到
say @l[ (0, (* + 1) * 2 ... *)[^3] ];
编辑:
一步使用一个变量并为其分配一个表达式
好吧,赋值的结果就是赋值,如果那是你mean/want,所以如果你坚持使用while
循环,这可能对你有用。
my @l = <a b c d e f g h i j k>;
my $i = -1; say @l[ $i = ($i + 1) * 2 ] while $i < 3;
my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[($=$i,$i=($i+1)*2)[0]] while $i < 7'
a
c
g
使用 $
作弊。不然不行...
我原以为 ($i,$i=($i+1)*2)[0]
会成功。
我正在尝试使用一个变量并在一步中为其分配一个表达式:
给定的(示例)代码
my @l=<a b c d e f g h i j k>;
my $i=0;
while $i < 7 {
say @l[$i];
$i= ($i+1) * 2;
}
# Output:
# a
# c
# g
所需功能:
my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[$i =~ ($i+1) * 2] while $i < 7;
# Here, first the @l[$i] must be evaluated
# then $i must be assigned to the expression
# ($i+1) * 2
# (The =~ operator is selected just as an example)
# Output:
# The same output as above should come, that is:
# a
# c
# g
在使用变量 $i
之后,(示例)表达式 ($i+1) * 2
应该在一步中分配给它,并且应该 仅在数组索引 @l[$i =~ ($i+1) * 2]
即 while
的参数应该 而不是 被改变。
这里我以 Regex 方程运算符 =~
(检查和赋值运算符,AFAIK)为例。当然,在这种情况下,它是行不通的。
我需要 是否有任何操作员或一些解决方法来实现该功能?谢谢。
你是说,像这样的东西?
my @l = <a b c d e f g h i j k>;
say @l[ 0, (* + 1) * 2 ...^ * > 7 ]; # says a c g;
有点冗长:
my @l = <a b c d e f g h i j k>;
say @l[ 0, -> $i { ($i + 1) * 2 } ...^ -> $i { $i > 7 } ];
甚至
my sub next-i( $i ) { ($i + 1) * 2 };
my sub last-i( $i ) { $i > 7 };
my @l = <a b c d e f g h i j k>;
say @l[ 0, &next-i ...^ &last-i ];
编辑:或者,如果在下面的评论中你事先知道元素的数量,你可以去掉结束块并(简化?)到
say @l[ (0, (* + 1) * 2 ... *)[^3] ];
编辑:
一步使用一个变量并为其分配一个表达式
好吧,赋值的结果就是赋值,如果那是你mean/want,所以如果你坚持使用while
循环,这可能对你有用。
my @l = <a b c d e f g h i j k>;
my $i = -1; say @l[ $i = ($i + 1) * 2 ] while $i < 3;
my @l=<a b c d e f g h i j k>;
my $i=0;
say @l[($=$i,$i=($i+1)*2)[0]] while $i < 7'
a
c
g
使用 $
作弊。不然不行...
我原以为 ($i,$i=($i+1)*2)[0]
会成功。