Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Operator Precedence (unary nagation and exponentiation)

by Arien (Pilgrim)
on Jan 14, 2003 at 10:54 UTC ( [id://226796]=note: print w/replies, xml ) Need Help??


in reply to Operator Precedence (unary negation and exponentiation)

Python (python -c 'print -2**2') and Ruby (ruby -e 'print -2**2') do it this way, both commands will print -4.

While we are on the subject, what is going on here??

$ perl -le 'print (-2)**2' -2 $

Update: B::Deparse helps sometimes:

$ perl -MO=Deparse -e 'print (-2)**2' print(-2) ** 2; -e syntax OK

The following does work as intended:

$ perl -le 'print((-2)**2)' 4

— Arien

Replies are listed 'Best First'.
Re: Re: Operator Precedence (unary nagation and exponentiation)
by tommyw (Hermit) on Jan 14, 2003 at 11:00 UTC

    It must be a parsing error, I guess: perl -e '$v=-2; print $v**2' correctly produces 4. So my guess is that the parsing in your example is simply throwing away the **2 component.

    Why is another question...

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.

      Use -w!
      $ perl -wle 'print (-2)**2' print (...) interpreted as function at -e line 1. Useless use of exponentiation (**) in void context at -e line 1. -2

      Just like any other function, if the function name is followed by a left paren, it's taken as the start of the argument list. print (-2)**2 is parsed as (print (-2)) ** 2. This is even documented. From perldoc print:

      Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to termi- nate the arguments to the print--interpose a "+" or put parentheses around all the arguments.

      Abigail

        Good catch, I should have used -w... sigh

        Arien mumbles something about how anybody can forget to put in switches now and then. ( -f ;-)

        — Arien

      Try perl -e '$v = 2; print -$v ** 2;'

      This the use of unary negation that is the subject of the thread.


      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

        But if you look at the problem that Arien posed, the answer doesn't just have the incorrect sign, it's also got the wrong magnitude.

        --
        Tommy
        Too stupid to live.
        Too stubborn to die.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2025-01-22 11:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which URL do you most often use to access this site?












    Results (63 votes). Check out past polls.