How to get variable calculated inside simple program to be used inside perl script?

Viewed 76

Within the perl script I have to call simple program that calculates psnr. I do it by:

$psnr_command_line = '';
$psnr_command_line = "/snr file1 file2 width height"

After I created command line, I simply call the system in perl:

$psnr_Y = system ($psnr_command_line);

In this case system returns 0 if command is successfully executed. But I need something else to be stored in $psnr_Y. Of course I need actual value of the psnr that has been calculated inside the program.

So, till now I have the following. Inside simple snr program I print result of the calculations (psnr in this case), so on command line after I run perl script I get printed something like these: P=65535.000000 MSE=304531.729854 PSNR=41.493141dB

I was wandering if somehow I can get PSNR value to $psnr_Y value in perl? Maybe somehow to redirect print to perl's variable and than simple parse that line to get PSNR?

Any ideas? Any other approaches are welcome.

Thank you.

1 Answers

I think that you are looking for the backticks operator:

$psnr_Y = `$psnr_command_line`;

Unlike function system(), which returns the system exit code of the command, the backticks operator return the output of the program (ie what it sent to STDOUT).

Once the command is executed, you can parse the result with a regex, like:

my ($val) = ($psnr_Y =~ m/PSNR=(\S+)/);

Reference: perlop - Quote-Like-Operators:

STRING A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.

Related