Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filehandle for Output from System Command in Perl

Is there a filehandle/handle for the output of a system command I execute in Perl?

like image 996
syker Avatar asked Jul 14 '10 00:07

syker


People also ask

How do I give a system a command in Perl?

The system() Function in Perl #!/usr/bin/perl $PATH = "I am Perl Variable"; system('echo $PATH'); # Treats $PATH as shell variable system("echo $PATH"); # Treats $PATH as Perl variable system("echo \$PATH"); # Escaping $ works.

What does system do in Perl?

Perl's system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.


2 Answers

Here's an example of establishing pipes between your script and other commands, using the 3-argument form of open:

open(my $incoming_pipe, '-|', 'ls -l')             or die $!;
open(my $outgoing_pipe, '|-', "grep -v '[02468]'") or die $!;

my @listing = <$incoming_pipe>;          # Lines from output of ls -l
print $outgoing_pipe "$_\n" for 1 .. 50; # 1 3 5 7 9 11 ...
like image 75
FMc Avatar answered Sep 23 '22 00:09

FMc


Yes, you can use a pipe like this:

open(my $pipe, "ls|") or die "Cannot open process: $!";
while (<$pipe>) {
    print;
}

See the documentation for open for more information, and perlipc for a complete description of pipe operation.

like image 33
Greg Hewgill Avatar answered Sep 25 '22 00:09

Greg Hewgill