|XP is just a number|
Re: variable declaration questionby Tommy (Chaplain)
|on Jan 18, 2013 at 21:49 UTC||Need Help??|
What's the difference between "my $var;" and "my ($var);" in variable declaration?
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