What is the difference between: 'my $var = 1' vs. 'my ( $var ) = 1'?

--0016e6d9a0572cce9a0484af2d41
Content-Type: text/plain; charset=UTF-8

At the introductory level it seems like I have often seen code like this:

use strict;

my $var = 1;

And as I review other peoples' scripts I have often encountered code like
this:

use strict;

my ( $this, $that, $the_other );

Which I interpreted as a mechanism to declare a number of scalar variables
with a minimum of typing.  But lately I've been seeing this syntax and I was
wondering if it was fundamentally different (and somehow more desirable):

use strict;

my ( $var ) = 1;

As if $var is being declared in a list context; what, if anything, do I get
by including parentheses when declaring a single variable?

Thanks,

--Marc

--0016e6d9a0572cce9a0484af2d41--
0
marcperryster
4/20/2010 6:23:38 PM
perl.beginners 29388 articles. 4 followers. Follow

2 Replies
868 Views

Similar Articles

[PageSpeed] 45
Get it on Google Play
Get it on Apple App Store

On Tue, Apr 20, 2010 at 2:23 PM, Marc Perry <marcperryster@gmail.com> wrote:
> As if $var is being declared in a list context; what, if anything, do I get
> by including parentheses when declaring a single variable?

I'm new to this myself, but it appears to alter the context of the
statement. Take the following:

    #!/usr/bin/env perl

    use strict;
    use warnings;

    $, = $\ = "\n";

    my @a = ("element1", "element2", "element3");

    my $x = @a;
    my ( $y ) = @a;

    print $x, $y;

    # EOF

The output should be:

3
element1

In the first case, the context is scalar, which results in the element
count being assigned to $x instead of the element(s). In the second
case, the context is list context, I think, which results in the first
element of the array being assigned to the variable $y. I'm not clear
on how to properly explain this, but to me it appears to make a list
of lvalues (assignables) and then moves the data from corresponding
positions on the right side of the equals sign to the left. Again,
there's probably a much better (and more correct) way to explain that.
;)

In other words, using or not using parenthesis can be context
sensitive so you need to know what you're doing with it. If you're
just declaring a normal variable, as in your example where you assign
it 1, then it doesn't seem to technically matter which you use, but
you're probably preferred to NOT use parenthesis because it's
unnecessary and might even be confusing if you are (and if the context
of the right-side changes then the meaning will change).

???

`perldoc perldata' appears to cover context somewhat:

http://perldoc.perl.org/perldata.html#Context

-- 
Brandon McCaig <bamccaig@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamccaig@castopulence.org>
0
bamccaig
4/20/2010 6:58:48 PM
On 4/20/10 Tue  Apr 20, 2010  11:23 AM, "Marc Perry"
<marcperryster@gmail.com> scribbled:

> At the introductory level it seems like I have often seen code like this:
> 
> use strict;
> 
> my $var = 1;
> 
> And as I review other peoples' scripts I have often encountered code like
> this:
> 
> use strict;
> 
> my ( $this, $that, $the_other );
> 
> Which I interpreted as a mechanism to declare a number of scalar variables
> with a minimum of typing.  But lately I've been seeing this syntax and I was
> wondering if it was fundamentally different (and somehow more desirable):
> 
> use strict;
> 
> my ( $var ) = 1;
> 
> As if $var is being declared in a list context; what, if anything, do I get
> by including parentheses when declaring a single variable?

You put the left-hand side into list context, which forces the right-hand
side of the assignment into list context. Perl will interpolate the scalar
value 1 into a list for you, yielding the one-element list (1). The first
element of the right-hand side (1) will then be assigned to the first
element of the left-hand side ($var).

Therefore, you gain nothing except to confuse your readers. That line is
better written as:

my $var = 1;


0
jimsgibson
4/20/2010 9:42:44 PM
Reply:

Similar Artilces:

''''''''''''''''''''
Name: haznen Email: haznenatyahoodotcom Product: Gran Paradiso Alpha 8 Summary: '''''''''''''''''''' Comments: '''''''''''''''''''''''''''''''''''' Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20061204 UGES/1.7.2.0 GranParadiso/3.0a1 From URL: http://www.mozilla.org/projects/granparadiso/ Note to readers: Hendrix gives...

'''''
Name: mario Email: ramar17atfastwebnetdotit Product: Gran Paradiso Alpha 2 Summary: ''''' Comments: K: Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a2) Gecko/20070206 GranParadiso/3.0a2 ...

ok(1,1) vs. ok ('foo','foo') in Test::More
=2D----BEGIN PGP SIGNED MESSAGE----- Moin, is there a re reason that the following warns: % perl -MTest::More -le 'plan tests =3D> 1; ok (1,1)' 1..1 # You named your test '1'. You shouldn't use numbers for your test names. # Very confusing. and this not: ok 1 - 1 % perl -MTest::More -le 'plan tests =3D> 1; ok ('foo','foo')' 1..1 ok 1 - foo This has prevented me from "converting" several huge old testsuites from=20 "use Test;" to "use Test::More;" because I know that I wo...

Argument '1': cannot convert from 'object' to 'int'
 I am calling a function from a label control in my gridview.. <asp:Label ID="Label1" runat="server" Text='<%# ShowCategoriesForPID(Eval("pol_id")) %>'/> But i get following error when i compile -error CS1503: Argument '1': cannot convert from 'object' to 'int'  pol_id is an integer value and my function receives it as an integer argument.  I dont know whats wrong? The "Eval" function returns an object. To need to cast it's result: <asp:Label ID="Label1" runat="s...

Global Variables: 'my' vs 'use vars'
Hello, All: I've never been very good at scoping so it it's no surprise that this confuses me: When declaring variables at the beginning of a script, what is the difference between 'my' and 'use vars'? -- Eric P. Los Gatos, CA On Thu, 2002-03-28 at 14:55, eric-perl@pretorious.net wrote: > Hello, All: > > I've never been very good at scoping so it it's no surprise that this > confuses me: > > When declaring variables at the beginning of a script, what is the > difference between 'my' and 'use...

'do' won't 'do' if '/'
Greetings to All from Au, Have a NetWare Perl 5.8.4 and wanted to tweak File\Spec\NW.pm to try and standardise on '/' separators. If I run a test script (t/uni/lower.t) with an unmodified NW.pm, it calls t/uni/case.pl, that, in case.pl, (when the path separators are '\'), the $file is '..\lib\unicore\To\Lower.pl' and the following code portion works, with $simple getting a returned table: sub casetest { my ($base, $spec, $func) = @_; my $file = File::Spec->catfile(File::Spec->catdir(File::Spec->updir, "lib", &qu...

urgent gettting '$var' as a String 'value of $var'
------=_NextPart_000_000E_01C1B6E8.F2271500 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all,=20 Sure i m the only one doing perl in the week-end, the mailinglist is = deserted. I' m tryig to generate dynamic SQL statements. I have a problem on getting a WHERE over 'varchar' type fields. for ($i =3D0; $i<scalar(@where); $i+=3D2){ #pour une entree a la table de hash avec en sortie un ensemble de = atts=20 #on en selectionne un aleatoirement sur le quel portera le where @tabAttrs =3D ...

'etc' and 'var' equivalents?
I get the feeling I'm overlooking something obvious, but I don't know what it is. A typical UNIX application will be installed something like: binaries: /usr/bin man pages: /usr/man config files: /etc data;state: /var MakeMaker supports various "INSTALL...BIN..." and "INSTALL...MAN..." options to adjust the locations of the "binaries" and "man pages" aspects of the application. That's fine; I'm happily using those. But I can't see how to specify the "config files" and "da...

'''
Name: L Lachowsky Email: e2brutus_10atyahoodotcom Product: Firefox Summary: ''' Comments: why duddn this surprise me... I change default server from IE to Mozilla, and then i get error messages. well, shud I decide to not get on my computer with Mozilla..or shud I risk security breeches with IE....hmmm at least i can get on the internet with IE Browser Details: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5 From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this fee...

Why I can't login in 'host' or 'admin' account when i upgrade to 3.1.1 from 3.1.0
Hi,I unzip DNN3.1.1 package and conver to my DNN original directory (ver 3.1.0) and install successfully.But when i login in 'host' or 'admin' account, it display 'Login Failed' ,so i tried to clean cookies in IE and also delete my portal aliases in C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\. But it still can't login by any account.Anyone have an idea what's wrong? I can't swear to this, but it seems I've had problems in the past with account resets in this situation. Have you tried logging in as Host with the default password "host"...

Cast from type ''''DBNull'''' to type ''''String'''' is not valid.
How do I avoid getting this error: Cast from type ''''DBNull'''' to type ''''String'''' is not valid. I am trying to get values from the database into a form for updating using a Datareader, SQL is set to allow nulls for certain fields as they are not required but the only way I can get the form to display is by adding a space in SQL. Is there another way around this? Check if it is equal to DBNull.Value first and if it is, don't do the cast.Stanley Tan theSpoke Blog Where in the code does it need to go? I am using the following and it's the profile that isn't always requi...

table_info('','','','%') cannot return any types
I was recently confirming table_info special cases and discovered the case for getting table_types cannot work. table_info('','','','%') should return a list of table types but it returns a list of empty strings instead: my @types = $h->tables('', '', '', '%'); print "all types:\n", join("xxx\n", @types), "\n"; # should output something like: # "dbo" # "INFORMATION_SCHEMA" # "sys" # and actually outputs: xxx xxx It seems to be down to the following ...

'returns' vs 'of'
I don't like the assignments of 'returns' and 'of'. I think it is easily confused. I've written foo (Int $x) returns Int in examples and nobody noticed. As formal documentation, that scans right as the outer perceived return value type. But no, it's supposed to be foo (Int $x) of Int instead. The returns keyword affects the implementation of the function, not the external contract. Yet, if returns is missing it uses the of value by default, but if the of is missing it does not give static type checking to the caller, rather than using the sam...

what does 'No overload for method 'Insert' takes '1' arguments' mean?
code that caused this error: line AddInBookSqlDataSource2.Insert(item);protected void inbookButton_Click(object sender, EventArgs e){ try{ AddInBookSqlDataSource1.Insert(); }catch (Exception ex){ uploadSPoneLabel.Text = "Saved Failed: SP One" + ex.Message; }foreach (ListItem item in authorsListBox5.Items){ try{ AddInBookSqlDataSource2.Insert(item); saveStatusLabel.Text = "Save Successful: SP Two"; }catch (Exception ex1){saveStatusLabel.Text = "Save Failed: SP Two" + ex1.Message; } } } any help appreciated Thanks in advance At a surface leve...

Web resources about - What is the difference between: 'my $var = 1' vs. 'my ( $var ) = 1'? - perl.beginners

Difference - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

3Q EARNINGS: Mark Zuckerberg on the Differences Between Messenger and WhatsApp
When Facebook announced its intent to acquire cross-platform messaging application WhatsApp in February, questions surfaced on whether WhatsApp ...

Facebook Tips: What’s the Difference between Top News and Most Recent?
The following is part of our series, Facebook Tips, which answers some of the most commonly asked questions about using Facebook. While we hope ...

Can You Spot the Difference?
The shamelessness on the part of Lenovo is almost breathtaking. Update: And then there’s Samsung’s new TV interface : white frosted translucent ...

Sole difference in tourism stakes
A GIANT blue stiletto heel dubbed Taiwan’s “shoe church” is bringing a touch of oversized glamour to the island’s southern coast.

Kurt Vile review: Line between fanatic and laconic the difference between a good and great show
Kurt Vile's blissfully laid-back recorded output doesn't quite gel with his live band, the Violators. They seem to always be pulling Vile back ...

H-bomb versus A-bomb: Understanding the difference
In a world more accustomed to talking about F-bombs than H-bombs, North Korea's claim that it has detonated one may have you asking what it is, ...

Not a dime's worth of difference? by @BloggersRUs
Not a dime's worth of difference? by Tom Sullivan A couple of articles bring to mind the "lesser of two evils" argument one often hears on ...

Is There Much Difference, Policy-Wise, Between Cruz, Rubio, Herr Trumpf And Ryan?
... Cruz or Rubio gets into the White House, we are in deep, deep trouble. Time to redouble our efforts for the one candidate who can make a difference ...

Sanders on differences with Clinton highlighted in campaign ad - Videos - CBS News
Democratic presidential candidate Bernie Sanders joins “CBS This Morning” from Burlington, Vermont, to discuss his latest campaign ad that explains ...

Resources last updated: 1/16/2016 3:50:46 AM