'how to implement odd numbers in a new array?
I want to output only the odd numbers from an array with the numbers from 1-100 in a new array. I have no idea how to do this.
use strict;
use warnings;
my @zahlen = (1..100);
foreach my $zahlen (@zahlen){
if ($zahlen % 2) {
print "$zahlen ist ungerade\n";
} else {
print "$zahlen ist gerade\n";
}
}
Solution 1:[1]
Just create new array and add the odd numbers
use strict;
use warnings;
my @zahlen = (1..100);
my @ungerade;
my $i = 0;
foreach my $zahlen (@zahlen){
if ($zahlen % 2){
$ungerade[$i] = $zahlen;
$i = $i + 1;
}
}
print "@ungerade"
Solution 2:[2]
You can also do it with grep
instead of a for-loop:
use strict;
use warnings;
my @zahlen = (1..100);
my @odds = grep { $_ % 2 == 1 } @zahlen;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nir Yossef |
Solution 2 | TLP |