Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Use of shift in Ternary Operator

by cheruvim (Initiate)
on Mar 22, 2008 at 17:38 UTC ( [id://675657]=perlquestion: print w/replies, xml ) Need Help??

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.

Apr 24, 2024 at 07:44 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://675657]
Approved by McDarren
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-24 07:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found