Home > other >  Perl: How to exit from main script if exit criteria is in a subscript?
Perl: How to exit from main script if exit criteria is in a subscript?

Time:12-29

I have a script main.pl which contains a loop over a list. This loop calls a subscript sub.pl which contains an exit criteria. When the criteria is met the program exit only the subscript but not the main script. How I have to change the code to stop the main script?

main.pl:

use strict; 
use warnings;
    
my @list = qw (a b c);

foreach my $i (@list) {    
    my $cmd = "sub.pl $i";
    print "$cmd\n";        
    system($cmd);        
}

sub.pl:

use strict; 
use warnings;    
use Cwd;

my $dir0 = getcwd;    
open my $LOG, ">>$dir0/log.txt" or die "Cannot open log.txt: $!\n";

my $value = $ARGV[0];

if ( $value eq 'b') {
    print "\nExit from script 2\n";
    exit;
}

print $LOG "Value is $value\n";
close $LOG;

The STDOUT is:

# sub.pl a
# sub.pl b
# 
# Exit from script 2
# sub.pl c
    

And the $LOG output is:

# Value is a
# Value is c

I would like that the script stops at value b.

CodePudding user response:

sub.pl is always exiting at the end of the script, not just when you exit explicitly exit somewhere else. You can exit with a specific code in sub.pl:

exit 1 if $value eq "b";

and then look for the exit code in main.pl:

system( $cmd ) and last

CodePudding user response:

Adding to @AKHolland's answer...

In general unfortunately can't just check the exit code of system($cmd) as perl makes life difficult by multiplexing a lot more information than just the exit code into $?. [1] I would recommend always using code like this to check it.

system($cmd);
last if ( ($? >> 8) & 255);

[1] https://perldoc.perl.org/functions/system

  • Related