Beautiful, I was having a problem testing all cases, which quickly showed the flaw in my logic, and I believe the and was throwing off the ternary - it has leftward associativity while ?: is rightward. The following changes looks like it will do what I want:

sub tt { my( $cookie, $param ) = @_; my $str = '(' . (defined $cookie ? $cookie : 'undef'); $str .= ',' . (defined $param ? $param : 'undef') . "):\t"; $str .= $cookie # I quickly realized it was necessary to test this here ? ( ( $param and $param =~ /^\d{1,2}$/ ) ? $param : $cookie +) # and I had to place a few more parens #: ( $param ? ($param and $param =~ /^\d{1,2}$/) : 5 ); # UPDATE: the above line was horribly translated from Grandf +athers. # It is corrected below, which also works when the same nest +ed # ternary idea (substituting /^\w{1,6}$/ for example) is use +d to # parse textual data. : ( ( $param and $param =~ /^\d{1,2}$/ ) ? $param : 5 ); # END UPDATE $str .= "\n"; return $str; } print tt( 4, 3 ); print tt( 4, 333 ); print tt( 444, 333 ); print tt( 2, undef ); print tt( undef, 1 ); print tt( undef, undef );

Prints:

(4,3): 3 (4,333): 4 (444,333): 444 # famous last words, but "this can never happen" ; +) (2,undef): 2 (undef,1): 1 (undef,undef): 5

++Grandfather, terse though your reply was (lacking explanation but sufficient code to guide me to the solution), I thank you for that quick sanity check.



--chargrill
$/ = q#(\w)# ; sub sig { print scalar reverse join ' ', @_ } + sig map { s$\$/\$/$\$2\$1$g && $_ } split( ' ', ",erckha rlPe erthnoa stJu +" );

In reply to Re^2: Nested ternaries by chargrill
in thread Nested ternaries by chargrill

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.