So here’s a fun code snippet I was working on and for the life of me can’t figure out what I’m doing wrong.
( chomp($CMD=`whereis blah | awk '{print \$2}'`) ||
chomp($CMD=`whereis cat | awk '{print \$2}'`) ) ?
(print "$CMD\n") : (print "Neither command exists.");
print "$CMD\n";
When executed, this always prints the empty string. As far as I can tell, the second assignment to $CMD never gets executed. I’ve included “blah” and “cat” purely for demonstration purposes. Ideally I’ll be checking for two commands that may or may not be installed on a given system. This is why I have the two assignments nested inside the conditional. If neither of these is found (therefore two empty strings) I’d like it to execute the false clause. But if one or the other of the commands does exist, I want it assigned to $CMD and the true clause to execute (just printing $CMD in the above example). I’ve played with various combinations but can’t seem to make this work.
I know this can be broken down and executed over several simpler statements to achieve the same result, but curiosity/stubbornness has gotten the better of me and I want to know why the above isn’t working. Any help you can provide would be much appreciated.
Perl’s
chompreturns the number of characters removed, NOT thechomp‘d string.But as a general answer to problems like this, if I can’t get something like that to work, I will fully expand it out (and simplify, removing things like external dependencies or things that just get in the way but aren’t relevant) until I can see everything working (for example printing return values between each set of statements). Once that is done, I will put the statements back together, piece by piece, checking along the way that it still works.
Once you are done, compare what you have now with what you had before, and that should tell you why it didn’t work (though more likely you will have figured it out along the way, like if one of the functions was returning something that you weren’t expecting).