cheruvim has asked for the wisdom of the Perl Monks concerning the following question:

Can someone explain to me why this is. Is the ternary operator some kind of list operator in disguise? Why does the context of shift need to be so explicit.

# WRONG! at least in 5.8.5 - context is ambiguous? my $thing = shift ? 1: 0 #RIGHT! $thing = shift() ? 1 : 0
if someone can point to the book that explains this, I would be greatful, otherwise it's a bug in my eyes because '?' is an operator and the interpretor upon hitting that operator as such and not a token should decipher the context of the shift.

Oct 05, 2025 at 20:56 UTC McDarren Moved from Snippets Section to SOPW

Replies are listed 'Best First'.
Re: Use of shift in Ternary Operator
by hipowls (Curate) on Mar 22, 2008 at 23:00 UTC

    The problem is that ? is ambiguous, is it part of a ternery operator or the start of a ?? match? From Perl Regular Expressions Reference

    ?pattern? is like m/pattern/ but matches only once. No alternate delimiters can be used. Must be reset with reset().
    puting () after shift resolves the ambiguity.

    Update:To explain further, shift expects a single argument which is an expression that evaluates to an array. If no argument is provided it defaults to @_. When perl sees shift ? it doesn't know if you mean

    shift(@_) ? 1: 2;
    or something like
    shift ?pattern? ? @a: @b;
    the parentheses forces the first interpretation and shift defaults to using @_.

Re: Use of shift in Ternary Operator
by jwkrahn (Abbot) on Mar 22, 2008 at 19:38 UTC