Reputation: 188
I wanted to create a conditional statement that would say if an element of an array is odd or even after getting the elements of the array from a line. Here's the code:
#! /usr/bin/perl
use warnings;
use strict;
my $numbers='23 45 34 12 9 3 56';
chomp $numbers;
my @getnum= (split(/ /, $numbers));
my $a;
if($getnum[0]>10){
$a=$getnum[0];
}
if($a%2==0){
print $a, " is even";
}
else{
print $a, " is odd";
}
Now the problem is I only did it for the first element. Is there a way I can do this for all elements without creating a conditional statement for each? Thanks for your help!
Upvotes: 0
Views: 78
Reputation: 2297
You need to use a for
(or foreach
) loop.
for my $n (@numbers) { # Loops over @numbers, assigning each to $n
if ( $n % 2 == 0 ) {
print "$n is even"
}
}
Additionally, this is rather un-idiomatic
my $numbers='23 45 34 12 9 3 56';
chomp $numbers;
my @getnum= (split(/ /, $numbers));
If you have a string you wish to split on whitespace, there is a special way to do that in Perl
split( ' ', $string );
This will split on arbitrary whitespace (and will strip leading and trailing whitespace), eg.
my @words = split( ' ', ' one two three ' );
# @words is ('one', 'two', 'three')
But if you are just hardcoding the number in your script itself, you can bypass the split
all-together and use the 'quote-words' syntax
my @numbers = qw( 23 45 34 12 9 3 56 );
Hope this helps.
Upvotes: 3