Another reason to use ?: rather than if/else. ?: saves your backreferences longer. The following code loses
$_ = 'abcdefghijk'; my($left) =1; if($left){ /ab(..)ef/} else{ /gh(..)jk/}; print "Caught $1\n"
because the $1 backreference is lost once you exit the scope of the if/else. So you can clutter things up with an extra variable:
$_ = 'abcdefghijk'; my($left, $var) =1; if($left){ ($var) = /ab(..)ef/} else{ ($var) = /gh(..)jk/}; print "Caught $var\n"
or you can use ?: and not lose the backreference
$_ = 'abcdefghijk'; my($left) =1; $left ? /ab(..)ef/ : /gh(..)jk/; print "Caught $1\n"
Of course, simple examples aren't as compelling as complex ones (because the amount of extra obscurity and work are small when the example is simple.) But if the pattern match is complex (eg when I'm trying to pull out $4 instead of $1) or when I'm ganging different patternmatches together. In the example below, $verbpat, $nounpat, $preppat are three similar patterns; I want to pull $4 out of each
$verbtest ? /$verbpat/ : $nountest ? /$nounpat/ : $preptest ? /$preppat/ : die 'No catch on $_'; $catch = $4;
So here's one more time that ?: is superior to if/else - when you want the backreference for a little longer while.

In reply to ?: and saving backreferences by throop

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.