IMPERATOR
IMPERATOR

Reputation: 287

Can you explain this nested conditional expression?

I can't decipher this line of code. Could someone please translate it into if / else statements?

I understand the basic CONDITION ? VALUE_IF_TRUE : VALUE_IF_FALSE pattern, but this line seems to break that.

$type = $self->{1}{_flag} & 2 ?
    $self->{2}{_flag} & 2 ? "A" : "B" :
    $self->{2}{_flag} & 2 ? "B" : "C";

Upvotes: 1

Views: 455

Answers (3)

ysth
ysth

Reputation: 98398

That's almost as cryptic as the equivalent

$type = (qw/C x B x A/)[ $self->{1}{_flag} & 2 + $self->{2}{_flag} & 2 ];

More seriously, nesting ternary operators in the true-branch is confusing. I'd use an explicit if/else. Or if I really wanted a ternary, I'd rearrange this to:

$type = $self->{1}{_flag} & 2 != $self->{2}{_flag} & 2
    ? 'B'
    : $self->{1}{_flag} & 2
        ? 'A'
        : 'C';

Upvotes: -1

Borodin
Borodin

Reputation: 126732

I think it's irresponsible to write code like that where the operator precedence is far from obvious

Using a mixture of if / else and conditional expressions it looks much clearer like this

if ( $self->{1}{_flag} & 2 ) {

    $type = $self->{2}{_flag} & 2 ? "A" : "B";
}
else {

    $type = $self->{2}{_flag} & 2 ? "B" : "C";
}

Upvotes: 6

ikegami
ikegami

Reputation: 385925

A couple of line breaks makes all the difference, although I've also added some parens to make it crystal clear.

$type = $self->{1}{_flag} & 2
   ? ( $self->{2}{_flag} & 2 ? "A" : "B" )
   : ( $self->{2}{_flag} & 2 ? "B" : "C" );

Upvotes: 5

Related Questions