0

I am having an issue with retrieving the correct information when attempting to run a shell command. When i run the command on the server i get the correct output, but i do not get the same when it is run through a perl script.

$test = `pkginfo | grep TestPackage | awk '{print $2}'`;
print "$test\n";

the output when running directly from the shell is:

TestPackage

While the output from the perl script is:

application TestPackage       Description

Why would this be different?

4

1 回答 1

5

The $2 is being interpolated by perl so that awk is only seeing the string print. Try:

$test = qx( pkginfo | awk '/TestPackage/{print \$2}' );
print "$test";

You can also prevent the interpolation by using single quotes as the delimiter to qx:

$test = qx' pkginfo | awk \'/TestPackage/{print $2}\' ';

Note that $test will have a trailing newline unless you chop it.

But, invoking awk from perl is not very perlish. Although using awk feels a lot cleaner, it may be better to do something like:

@test = map { m/^\S+\s+(\S+)/; $_ = $1 } grep { /TestPackage/ } qx( pkginfo );
于 2013-03-15T16:16:32.530 回答