Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a conditional and a loop in the same line?

Tags:

perl

I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

foreach (0 .. 10) {
    print $_ if $_ % 2;
}

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

[i for i in range(10) if i % 2]

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

like image 886
Li JY Avatar asked Oct 15 '25 19:10

Li JY


1 Answers

For elements of a list which are odd

$_%2 and print for 0..10;

or

$_&1 and print for 0..10;

Or one may want elements at odd indices where that 0..10 stands for array indices

my @ary = 0..10;

$_&1 and print $ary[$_] for 0..$#ary;

The syntax $#ary is for the index of the last element of array @ary.

The point being that Perl's and short-circuits so if the expression on its left-hand-side isn't true then what is on its right-hand-side doesn't run. (Same with or -- if the LHS is true the RHS isn't evaluated.)

If you indeed need array elements at odd indices can also do

my @ary = 0..10; 

print for @ary[grep { $_&1 } 0..$#ary];

All above print 13579 (no linefeed). In a one-liner, to enter and run on the command-line

perl -we'$_%2 and print for 0..10'

If you actually need to print each number on its own line, judged by a posted comment, replace print with say. For instance, for odd array elements from array @ary

$_%2 and say for 0..$#ary;

or, for array elements at odd indices

$_&1 and say $ary[$_] for 0..$#ary;

Add use feature 'say'; to the beginning of the program (unless it is enabled already by other loaded tools/libraries).

like image 75
zdim Avatar answered Oct 17 '25 08:10

zdim