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
both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.
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.
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) {
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");
I'd usually write this as:
$review = ( defined($model->test) ? 1 : '' );
where the parentheses are for clarity for other people reading the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With