I want the output to show which numbers are even and which are odd. Strangely, I only get 100 is odd
100 times. Does anyone know what I did wrong?
my @zahlen = (1..100);
my $zahlen = @zahlen;
foreach (@zahlen){
if (@zahlen % 2) {
print "$zahlen is even\n";
} else {
print "$zahlen is odd\n";
}
}
CodePudding user response:
You are using the wrong variables in the wrong places. You set $zahlen
to a constant value outside the loop (100). You can use it as the loop iterator variable instead.
Also, you should use the scalar $zahlen
instead of the array @zahlen
in the if
statement.
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";
}
}
Prints (I changed 100 to 10 to simplify the output):
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
CodePudding user response:
The code can be written in alternative more concise form
use strict;
use warnings;
use feature 'say';
my @zahlen = (1 .. 10);
say "$_ is " . (($_ % 2) ? "odd" : "even") for @zahlen;
Output
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