ado
ado

Reputation: 1471

Perl: Similar conditions in an if. How to make it shorter & nicer?

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

Answers (6)

AKHolland
AKHolland

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

teodozjan
teodozjan

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

lecstor
lecstor

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

darmat
darmat

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

William Pursell
William Pursell

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

Thilo
Thilo

Reputation: 262504

Maybe with the smart match operator:

if ( $self->{status} ~~ [1,2,3] ) {

Upvotes: 4

Related Questions