open OUTPUT, "| grep 'foo' > result.txt" or die "Failure: $!";
We can then write whatever we want to the "OUTPUT" filehandle. The Unix "grep"
command will filter out any text which doesn't contain the text "foo"; any text
which DOES contain "foo" will be written to "result.txt".
Don't Use OPEN
And for programs that only return a few lines of output, use back-ticks:
my $username = `whoami` or die "Couldn't execute command: $!";
chomp($username);
print "My name is $username\n";
You can also use the "qx//" operator, which is exactly equivalent to back-ticks
except that it allows you to choose your delimiter:
# All of the following are exactly equivalent
# to the above command that uses back-ticks.
my $username = qx/whoami/ or die "Couldn't execute command: $!";
my $username = qx(whoami) or die "Couldn't execute command: $!";
my $username = qx#whoami# or die "Couldn't execute command: $!";
No comments:
Post a Comment