Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the output of an external command in Perl?

I want to have output of Windows command-line program (say, powercfg -l) written into a file which is created using Perl and then read the file line by line in a for loop and assign it to a string.

like image 938
stack_pointer is EXTINCT Avatar asked Sep 25 '09 14:09

stack_pointer is EXTINCT


4 Answers

You have some good answers already. In addition, if you just want to process a command's output and don't need to send that output directly to a file, you can establish a pipe between the command and your Perl script.

use strict;
use warnings;

open(my $fh, '-|', 'powercfg -l') or die $!;
while (my $line = <$fh>) {
    # Do stuff with each $line.
}
like image 153
FMc Avatar answered Oct 19 '22 06:10

FMc


system 'powercfg', '-l';

is the recommended way. If you don't mind spawning a subshell,

system "powercfg -l";

will work, too. And if you want the results in a string:

my $str = `powercfg -l`;
like image 38
wallenborn Avatar answered Oct 19 '22 05:10

wallenborn


my $output = qx(powercfg -l);

## You've got your output loaded into the $output variable. 
## Still want to write it to a file?
open my $OUTPUT, '>', 'output.txt' or die "Couldn't open output.txt: $!\n";
print $OUTPUT $output;
close $OUTPUT

## Now you can loop through each line and
##   parse the $line variable to extract the info you are looking for.
foreach my $line (split /[\r\n]+/, $output) {
  ## Regular expression magic to grab what you want
}
like image 22
joealba Avatar answered Oct 19 '22 04:10

joealba


There is no need to first save the output of the command in a file:

my $output = `powercfg -l`;

See qx// in Quote-Like Operators.

However, if you do want to first save the output in a file, then you can use:

my $output_file = 'output.txt';

system "powercfg -l > $output_file";

open my $fh, '<', $output_file 
    or die "Cannot open '$output_file' for reading: $!";

while ( my $line = <$fh> ) {
    # process lines
}

close $fh;

See perldoc -f system.

like image 8
Sinan Ünür Avatar answered Oct 19 '22 04:10

Sinan Ünür