I'm trying to use a variable and assign an expression to it in one step:
The given (sample) code
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
The desired functionality:
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
After the variable $i
is used, the (sample) expression ($i+1) * 2
should be assigned to it in one step and that should take place solely inside the array index @l[$i =~ ($i+1) * 2]
i.e. the argument of while
should not be changed.
Here I took the Regex equation operator =~
(check and assign operator, AFAIK) just as an example. In this context of course, it did not work.
I need to Are there any operators or some workaround to achieve that functionality? Thank you.
You mean, something like this?
my @l = <a b c d e f g h i j k>;
say @l[ 0, (* + 1) * 2 ...^ * > 7 ]; # says a c g;
A little bit more verbose:
my @l = <a b c d e f g h i j k>;
say @l[ 0, -> $i { ($i + 1) * 2 } ...^ -> $i { $i > 7 } ];
Or even
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 ];
Edit: Or, if as in the comment below you know the number of elements beforehand, you can get rid of the end block and (simplify?) to
say @l[ (0, (* + 1) * 2 ... *)[^3] ];
Edit:
using a variable and assigning an expression to it in one step
Well, the result of an assignment is the assigned value, if that is what you mean/want, so if you insist on using a while
loop, this might work for you.
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
A bit of cheating using $
. Otherwise, it didn't work...
I would have thought ($i,$i=($i+1)*2)[0]
would have done the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With