I'm evaluating whether or not certain variables match expected values. The variables are set in memory by a certain program, the values of which can be access from the shell with a custom program.
I'm piping the output of the shell command to awk to get the specific field I want and then I want to run it through perl to see if it matches the expected value. For example,
ysgrp autostart | awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'
However, I'm getting complaints from perl about compilation errors near "} else". How does one handle if/then/else logic in a perl one-liner?
The "else if" keyword is spelled elsif in Perl. There's no elif or else if either. It does parse elseif , but only to warn you about not using it.
Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the ...
You can't use an else
condition in a postfix conditional. You can either use a ternary conditional operator like this:
perl -e 'print /on/ ? "True" : "False"'
Or use explicit blocks like this:
perl -e 'if ( /on/ ) { print "True" } else { print "False" }'
This part:
awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'
can be handled in perl (if I remember awk correctly):
perl -F/:/ -lane 'print $F[0] =~ /on/ ? "True" : "False"'
Note the use of the -n
switch, without which your perl one-liner will not work. Also note the -l
switch, which adds a newline to your print, which is something I assume you want. Otherwise your output will be something like:
TrueTrueTrueFalseTrueFalse
You could do:
... | perl -ne 'print /on/ ? "True" : "False"'
but please don't! You'd be better off doing:
... | grep -qF on && echo True || echo False
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