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 o开发者_运维问答ther 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 chomp
returns the number of characters removed, NOT the chomp
'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).
chomp
returns the number of characters removed, not the resulting string.
If blah
cannot be found, then the output of whereis blah
is just
blah:
and the output of whereis blah | awk '{print $2}'
is just an empty line (i.e., just a newline character). In your Perl script, $CMD
would initially be set to "\n"
, which would then be chomp
'd away. BUT since chomp
would return 1, the second command (whereis cat ...
) would not get executed. So your program is doing exactly what you told it to.
I would try simpler statements and try to get a different result.
#!/usr/bin/env perl
use 5.10.0;
use utf8;
use strict;
use autodie;
use warnings qw< FATAL all >;
use open qw< :std OUT :utf8 >;
END {close STDOUT}
$| = 1;
sub whence(_) {
my($aout, $path) = shift();
for my $bin (split /:/ => $ENV{PATH}) {
return $path if -f -x ($path = "$bin/$aout");
}
# FALLTHROUGH
}
say "$_: ", whence for @ARGV;
精彩评论