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";
}
}
CodePudding user response:
You can also do it with grep
instead of a loop:
use strict;
use warnings;
my @zahlen = (1..100);
my @odds = grep { $_ % 2 == 1 } @zahlen;
CodePudding user response:
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"
CodePudding user response:
Here is an example of how to output odd numbers:
use feature qw(say);
use strict;
use warnings;
my @zahlen = (1..100);
sub check_odd { say if $_[0] % 2 }
check_odd($_) for @zahlen;