Search code examples
perlreturn-valuesubroutine

Perl: How to check what is being returned from a subroutine


I have a subroutine that will return two hashes when all goes well. But the sub checkouts output of command and if it matches a certain pattern, it returns with "-1". Is there anyway to check the return of the subroutine from where I called it?

Kinda like:

if (RETURN_VALUE == -1){
   do something}
   else
   go as normal with the hashes

Solution

  • You function should return references to the two hashes on success and nothing upon failure. Then you can just check the truth value of the function call.

    sub myfunc {
        my %hash1;
        my %hash2;
        return (\%hash1, \%hash2);
    }
    
    my $ref1;
    my $ref2;
    unless (($ref1, $ref2) = myfunc()) { 
        print "Something went wrong\n";
    } else { 
        print "OK\n";
    }