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.
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.
}
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`;
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With