Hello jmsnet, and welcome to the Monastery!
2) ... if the ticket request or data request fails then the return value is undef. Each time i call the subroutine and get a return value i then have to do an if loop to check whether the value is defined or not. Is there a more efficient way of doing this because I am basically just repeating if statements after each call eg. if i didn't get a ticket I could just call exit in the subroutine but it seems more logical to me and easier to follow if I handle it outside the subroutine.
You’re right, a subroutine should never exit. But it can die (Perl’s way of throwing an exception):
sub get_ticket { my ($rest_client, $sdn_controller) = @_; my $ticket; ... die "\$ticket undefined in get_ticket()" unless defined $ticket; return $ticket; }
and then in the calling code you’re free to handle the exception or not. If you don’t, it propagates up through the call stack until it reaches the top level and the script dies. If you want to change the way the script exits, catch the exception at the top level:
MAIN: { my $result = 0; # normal termination eval { ... # main code goes here } $result = 1 if $@; # abnormal termination exit $result; }
See die, eval, also Try::Tiny and TryCatch.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: subroutine and good practices
by Athanasius
in thread subroutine and good practices
by jmsnet
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |