Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: understanding this syntax

by molecules (Monk)
on Oct 01, 2010 at 17:31 UTC ( #862994=note: print w/replies, xml ) Need Help??

in reply to understanding this syntax

I don't know if the question was edited, but at this moment the question says "Why do we have parentheses around FOO/BAR in the hash?".

Hash assignment takes a list. The following shows that a lack of parentheses makes a difference:

use strict; use warnings; use constant FOO => 10; use constant BAR => 20; use Data::Dump qw/ dump /; my %BAZ = ( FOO() => 1, BAR() => 1 ); my %BOO = ( FOO => 1, BAR => 1 ); my %BAH = FOO => 1, BAR => 1; print 'BAZ: ' . dump(\%BAZ) . "\n"; print 'BOO: ' . dump(\%BOO) . "\n"; print 'BAH: ' . dump(\%BAH) . "\n";

This prints:

Useless use of a constant (BAR) in void context at temp/ line 17.
Odd number of elements in hash assignment at temp/ line 17.
BAZ: { 10 => 1, 20 => 1 }
BOO: { BAR => 1, FOO => 1 }
BAH: { FOO => undef }

Both comma operators (i.e. " => " and " , ") have lower precedence than the assignment operator " = ". Thus the assignment operator takes only the first argument to its right, which for the hash %BAH is the value for the constant FOO. It doesn't even "see" anything to the right of the first fat comma  => or even the comma itself.

Using parentheses around everything to the right of the assignment operator creates a list that the assignment operator in turn uses to create the hash.

Perl is an "Operator-oriented language" as chromatic mentions in his blog post Perl and the Least Surprised.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://862994]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2018-06-18 00:42 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (107 votes). Check out past polls.