Reputation: 423
There are two declared variables, I want to evaluate at same time if both exist (are TRUE).
my @array = (1,2);
my $scalar = 0;
if (@array && $scalar){
print "success\n";
}
&&
does not work. Is there another operator or do I have to create 2 if-state?
I expected it to print success
.
Upvotes: 0
Views: 375
Reputation: 37
try this
my @array = (1,2);
my $scalar = 0;
if (scalar @array && defined $scalar){
print "success\n";
}
Upvotes: -1
Reputation: 46187
The code that does not work is not the code you posted.
perl -E 'my @array = (1,2); my $scalar = 1; if (@array && $scalar) { say "True!" } else { say "False" }'
True!
perl -E 'my @array = (); my $scalar = 1; if (@array && $scalar) { say "True!" } else { say "False" }'
False
Edit: More examples in response to kmxillo's comment:
perl -E 'my @array = (1,2); my $scalar = 0; if (@array && $scalar) { say "True!" } else { say "False" }'
False
perl -E 'my @array = (1,2); my $scalar = 0; if (@array && defined $scalar) { say "True!" } else { say "False" }'
True!
The number 0 is considered to be a false value (along with undef
, the empty string, the empty array, and the string "0"), so setting $scalar
to 0 makes @array && $scalar
false. To keep it true when $scalar
is 0, test defined $scalar
instead.
Upvotes: 3
Reputation: 1747
If you consider array true when it has more than zero elements, then your if statement looks fine and should work as expected.
This program:
my @array = (1,2);
my $scalar = 1;
if (@array && $scalar) {
print "TRUE!\n";
}
prints TRUE
.
Why do you think &&
does not work?
Upvotes: 1