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

后端 未结 7 1412
闹比i
闹比i 2020-12-03 13:45

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

7条回答
  •  爱一瞬间的悲伤
    2020-12-03 14:14

    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.

提交回复
热议问题