Reputation: 811
I have the following code:
if (defined(@hash{qw{value1 value2 value3}})){
# code block
}
What I want to happen is for the code block to execute if either $hash{value1}, $hash{value2} or $hash{value3} is defined. However, what happens is that the code block executes if and only if $hash{value3} is defined:
$hash{value3}='yep, here!';
if (defined(@hash{qw{value1 value2 value3}})){
print "yay!";
}
Output:
yay!
But:
$hash{value2}='yep, here!';
if (defined(@hash{qw{value1 value2 value3}})){
print "yay!";
}
Output:
<nothing>
Why isn't this working right and what should I do?
Upvotes: 1
Views: 40
Reputation: 50667
perldoc -f defined doesn't mention hash slice, and warnings don't warn you about this, but what you want is,
if (grep defined, @hash{qw{value1 value2 value3}}) {
# code block
}
as defined()
forces scalar context, and slices in such case return last element.
use warnings;
sub context {
print wantarray ? "LIST" : "SCALAR";
}
my $def = defined(context());
outputs SCALAR
Upvotes: 2