Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: variable declaration question

by Tommy (Chaplain)
on Jan 18, 2013 at 21:49 UTC ( #1014136=note: print w/replies, xml ) Need Help??

in reply to variable declaration question

What's the difference between "my $var;" and "my ($var);" in variable declaration?

The difference is that the first version enforces scalar context on the assignment, and the second imposes list context. (Mark Jason Dominus explains this better.)

These may seem like insignificant differences, but can lead to nasty bugs in code if, say, you have a manager who decides to make it a "coding practice" to put parens (around) (all) (variable) (declarations) (everywhere) in the name of "consistency". *see footnote1

Parens() aren't a matter of style. For the most part, parenthesis serve three purposes in perl: they impose list context, they denote/force sub/method invocation, and assist in forcing precedence in order of operations on an expressions with multiple invocants.

For single variable assignment, you usually want scalar context, which is why it should _NEVER_ be a coding practice to use one form or the other because it isn't an issue of style -- it's an issue of behavior.

Furthermore, when you use my($foo) = $obj->method() as a matter of practice, then it completely breaks upstream interfaces using the wantarray() builtin to produce polymorphic results for you. And if you're a real jerk, you'll blame the designer of the upstream interface for your own lack of understanding. *facepalm*

This wouldn't be such a big deal to me if it hadn't been such a bad experience to learn it the hard way. I'm pretty sure that the perils of misunderstanding scalar vs. list context are a big reason why it is one of the first things many Perl books and instructors cover nowadays, and if they don't, they #$%@! well should.

1: my($sad_experience) = (it, has, happened, to, me, ;_;)

A mistake can be valuable or costly, depending on how faithfully you pursue correction

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2018-05-21 17:23 GMT
Find Nodes?
    Voting Booth?