Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

perl - Assigning using ternary operator?

I am on Perl 5.8 and am needing to assign a default value. I ended up doing this:

if ($model->test) {
    $review = "1"
} else {
    $review = ''
}

The value of $model->test is going to be either "1" or undefined. If there's something in $model->test, set $review to "1" otherwise set it equal to ''.

Because it's not Perl 5.10 I can't use the new swanky defined-or operator. My first reaction was to use the ternary operator like this...

defined($model->test) ? $review = "1" : $review = '';

but that didn't work either.

Does anyone have an idea how to assign this more efficiently? Janie

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd usually write this as:

$review = ( defined($model->test) ? 1 : '' );

where the parentheses are for clarity for other people reading the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...