Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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/hash_test.pl line 17.
Odd number of elements in hash assignment at temp/hash_test.pl 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.


Comment on Re: understanding this syntax
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2014-12-18 09:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (48 votes), past polls