The other day I ran into something that I thought was a little odd. First off, we know that the ternary operator can be used as an lvalue as in:

$flag ? $on : $off = $value;

And in fact, this works too:

$flag ? @array1 : @array2 = qw/This that the other/;

This works too.......

sub testthis { $_[0] = "Hi mom.\n"; } testthis ( $flag ? $yes : $no ); foreach ( $yes, $no ) { print "$_\n" if defined $_; }

But things break down in this push example:

my $condition = int rand 2; my ( @array1, @array2 ); my $stuff = "This, that, and the other"; push( ( $condition ? @array1 : @array2 ), $stuff );

That example gives a big fat compilation error.

I wonder if it has anything to do with the fact that neither of these succeed in modifying the parameter:

# First example; nothing gets assigned to @array; my @array; sub testthis { @_ = qw/This that and the other/; } testthis ( @array ); # Second example; nothing gets assigned to @array1 or @array2. # But no compiletime errors are generated either: my $condition = int rand 2; sub testthis { @_ = qw/This that and the other/; } my ( @array1, @array2 ); testthis( $condition ? @array1 : @array2 );

In a way, it seems like the ternary behavior within push must be related to the behavior of trying to assign to modify the contents of an array passed as a parameter to a sub. But the push version generates a compiletime error, and the non-push version just doesn't perform the modification of the parameter.

Has DWIM broken down? Is this defined behavior? I haven't found the trinary / push behavior documented. Perhaps I've missed something, but it's interesting to ponder anyway.


Dave


In reply to Ternary operator can't be used as first argument of push by davido

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.