Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 267
Jane Wilkie Avatar asked Jan 19 '12 20:01

Jane Wilkie


People also ask

Can we use assignment operator in ternary operator?

both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.

How do you use a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is a ternary operator with example?

The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if else block. For example, consider the below JavaScript code. var num = 4, msg = ""; if (num === 4) {

What is the use of ternary operator in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");


1 Answers

I'd usually write this as:

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

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

like image 72
Greg D'Arcy Avatar answered Sep 21 '22 00:09

Greg D'Arcy