Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner if else logic

Tags:

perl

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?

like image 261
phileas fogg Avatar asked May 08 '12 17:05

phileas fogg


People also ask

Does Perl have Elseif?

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.

What are conditional statements in Perl?

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 ...


3 Answers

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" }'
like image 97
friedo Avatar answered Sep 21 '22 11:09

friedo


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
like image 24
TLP Avatar answered Sep 22 '22 11:09

TLP


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
like image 27
William Pursell Avatar answered Sep 18 '22 11:09

William Pursell