Perl one-liner if else logic

I evaluate whether certain variables match the expected values. Variables are set in memory by a specific program, the values ​​of which can be accessed from the shell using a special program.

I pass the output of the awk shell command 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 instance,

ysgrp autostart | awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'

However, I am getting complaints from perl about compilation errors next to "} else". How to handle if / then / else logic in single line perl?

+5
source share
4 answers

You cannot use a condition elsein postfix conditional. You can use the ternary conditional operator as follows:

perl -e 'print /on/ ? "True" : "False"'

:

perl -e 'if ( /on/ ) { print "True" } else { print "False" }'
+12

:

awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'

perl ( awk):

perl -F/:/ -lane 'print $F[0] =~ /on/ ? "True" : "False"'

-n, perl . -l, , , . :

TrueTrueTrueFalseTrueFalse
+3

It is impossible, with the exception of using the ternary operator ?:; syntax foo if bardoes not support else.

+1
source

You can do:

 ... | perl -ne 'print /on/ ? "True" : "False"'

but please don’t! You will be better off:

... | grep -qF on && echo True || echo False
+1
source

All Articles