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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.