Reputation: 1471
This is too long:
if ( $self->{status} == 1 ||
$self->{status} == 2 ||
$self->{status} == 3
){
$self->status(4);
} else {
croak "only 1,2 and 3 change to 4";
}
How would you make it nicer & shorter?
Upvotes: 1
Views: 95
Reputation: 4445
Maybe not the most efficient way in the world, but doesn't rely on experimental features or loops:
if($self->{'status'} =~ m/^(1|2|3)$/) { ... }
Upvotes: 0
Reputation: 913
If status is always an positive integer You may:
if($self->{status} < 4)
{
$self->status(4);
} else {
croak "only 1,2 and 3 change to 4";
}
Upvotes: 1
Reputation: 5707
not sure if it's nicer, but..
foreach my $x (1,2,3,4,5){
if (map{ $x == $_ ? 1 : () }(1,2,3) ){
print "is 1,2, or 3\n";
} else {
printf "is %s\n", $x;
}
}
Upvotes: 1
Reputation: 728
You could use the ternary operator:
$self->{status} ~~ [1,2,3] ? $self->status(4) : croak "only 1,2 and 3 change to 4";
Upvotes: 2
Reputation: 212248
If your perl is new enough to have smart match:
$self->{status} ~~ (1,2,3) and $self->status(4) or croak "...";
Upvotes: 0
Reputation: 262504
Maybe with the smart match operator:
if ( $self->{status} ~~ [1,2,3] ) {
Upvotes: 4