我怎样才能在偶数和奇数之间交替?

How can I alternate between even and odd numbers?

我希望输出显示哪些数字是偶数,哪些是奇数。奇怪的是,我只得到 100 is odd 100 次。有谁知道我做错了什么?

my @zahlen = (1..100);
my $zahlen = @zahlen;

foreach (@zahlen){
    if (@zahlen % 2) {
        print "$zahlen is even\n";
    } else {
        print "$zahlen is odd\n";
    }
}

您在错误的地方使用了错误的变量。您将 $zahlen 设置为循环外的常数值 (100)。您可以将其用作循环迭代器变量。

此外,您应该在 if 语句中使用标量 $zahlen 而不是数组 @zahlen

use warnings;
use strict;

my @zahlen = (1 .. 10);

foreach my $zahlen (@zahlen) {
    if ($zahlen % 2) {
        print "$zahlen is odd\n";
    }
    else {
        print "$zahlen is even\n";
    }
}

打印(我将 100 更改为 10 以简化输出):

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

代码可以写成更简洁的替代形式

use strict;
use warnings;
use feature 'say';

my @zahlen = (1 .. 10);

say "$_ is " . (($_ % 2) ? "odd" : "even") for @zahlen;

输出

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even