It's unusual to save the value of a comparison, but it is very common to use a variable in an if statement. Consider this code:

# get office_id for this office my $office_id = get_office_id(); if ($office_id) { # found an office } else { # no office found }

The hypothetical get_office_id() function could be written in such a way that the office id returned will either be a positive integer or undef if the office id cannot be found. Then the $office_id can be used directly in an if to test to result.

Of course, this will be wrong if 0 is a vaild office id. Then you need to do:

# get office_id for this office my $office_id = get_office_id(); if (defined $office_id) { # found an office } else { # no office found }

Although this is a common pattern it is actually not the best way to write functions in Perl. A better way is to separate the status code from the return value:

# get office_id for this office my ($ok, $office_id) = get_office_id(); if ($ok) { # found an office } else { # no office found }

That way there can be no confusion between the office id itself and the success of the call.

-sam


In reply to Re: Using scalar values as conditionals by samtregar
in thread Using scalar values as conditionals by amarceluk

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.