Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Perl on the command line to search the output of other programs?

As I understand (Perl is new to me) Perl can be used to script against a Unix command line. What I want to do is run (hardcoded) command line calls, and search the output of these calls for RegEx matches. Is there a way to do this simply in Perl? How?

EDIT: Sequence here is: -Call another program. -Run a regex against its output.

like image 204
alexwood Avatar asked Jan 22 '09 16:01

alexwood


1 Answers

my $command = "ls -l /";
my @output = `$command`;
for (@output) {
    print if /^d/;
}

The qx// quasi-quoting operator (for which backticks are a shortcut) is stolen from shell syntax: run the string as a command in a new shell, and return its output (as a string or a list, depending on context). See perlop for details.

You can also open a pipe:

open my $pipe, "$command |";
while (<$pipe>) {
    # do stuff
}
close $pipe;

This allows you to (a) avoid gathering the entire command's output into memory at once, and (b) gives you finer control over running the command. For example, you can avoid having the command be parsed by the shell:

open my $pipe, '-|', @command, '< single argument not mangled by shell >';

See perlipc for more details on that.

like image 52
ephemient Avatar answered Sep 28 '22 09:09

ephemient