我正在尝试使用一个变量,并在一个步骤中为其分配一个表达式:
给定的(样本)代码
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
Run Code Online (Sandbox Code Playgroud)
所需的功能:
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
Run Code Online (Sandbox Code Playgroud)
可变后$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;
Run Code Online (Sandbox Code Playgroud)
更加详细:
my @l = <a b c d e f g h i j k>;
say @l[ 0, -> $i { ($i + 1) * 2 } ...^ -> $i { $i > 7 } ];
Run Code Online (Sandbox Code Playgroud)
甚至
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 ];
Run Code Online (Sandbox Code Playgroud)
编辑:或者,如果像下面的注释中那样,您事先知道了元素的数量,则可以摆脱结尾块,然后(简化?)
say @l[ (0, (* + 1) * 2 ... *)[^3] ];
Run Code Online (Sandbox Code Playgroud)
编辑:
使用变量并在一个步骤中为其分配表达式
好吧,赋值的结果就是赋值,如果这就是您想要/想要的,那么如果您坚持使用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;
Run Code Online (Sandbox Code Playgroud)