0

Code of inter.pl is:

use strict;
use warnings;

my $var1=`cat /gra/def/ment/ckfile.txt`;  #ckfile.txt doesn't exist
print "Hello World";
exit 0;

Code of ext.pl

my $rc = system ("perl inter.pl");
print "$rc is rc\n";

Here, when I run "perl ext.pl", $rc is coming as 0.

Although file inside inter.pl (/gra/def/ment/ckfile.txt) doesn’t exist, I am getting $rc as 0.

I would want $rc to be != 0 (as in one way, it should be an error as file ckfile.txt doesn't exist) in this same scenario.

Note: I can't do any modification in inter.pl

How can it be implemented?

Thanks In Advance.

AskQuestionsP
  • 153
  • 1
  • 9
  • 1
    Difficult without modifying `inter.pl`. The error is in the child process (the process running `cat …`), the error code is available in `$?` after the child finishes, then execution of the script continues, including the last `exit 0` instruction. So, regardless the `ckfile.txt` exists or not, `ext.pl` always sees a "clean" run of `inter.pl`. – larsen Oct 07 '21 at 12:47
  • If you can't modify inter.pl, you should have mentioned that in your first question on the topic. – Shawn Oct 07 '21 at 14:19

1 Answers1

5

If you want the program to have an non-zero exit status, you'll need to replace the (useless) exit 0;.

my $var1=`cat /gra/def/ment/ckfile.txt`;
exit 1 if $?;

or

my $var1=`cat /gra/def/ment/ckfile.txt`;
die("Can't spawn child: $!\n") if $? == -1;
die("Child killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("Child exited with error ".( $? >> 8 )."\n") if $? >> 8;
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • I'd use the [`POSIX` functions](https://perldoc.perl.org/POSIX#WAIT) with `${^CHILD_ERROR_NATIVE}` to inspect the exit status instead of magic numbers and bit shifting. (Also, shouldn't `&&` be `&` in that?) – Shawn Oct 07 '21 at 16:51
  • @ikegami This script is just a sample. The actual script is very big and meaningful with the exit being an equally important function. Hence, can't remove exit 0. And, the second method you mentioned is not feasible as in a script code of 2000 lines, it is not possible to add this check always. – AskQuestionsP Oct 08 '21 at 10:39