Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re^4: Perl array declaring

by Laurent_R (Canon)
on Jun 01, 2013 at 22:09 UTC ( #1036510=note: print w/replies, xml ) Need Help??

in reply to Re^3: Perl array declaring
in thread Perl array declaring

Variables can be declared as many times as you like...

True only for global variables, and even then, not without warnings. Change your 'our' to 'my' and your program no longer works. You are creating new variables with the same name. Warnings inform you that the new variable masks an earlier declaration.

I surely understand what you meant to say and agree with what you intended to say, Bill, but lexical variables can indeed be declared as many times as you like, provided they are not declarred in the same lexical scope. For example, the following code declares the same lexical variable four times without any error or warning:

use strict; use warnings; my $var = 1; { my $var = 2; print $var, "\n", } print "$var \n"; foreach my $var (1..5) { print $var, "\n"; } print double(7); sub double {my $var = shift; return 2 * $var;}

and happily prints:

$ perl 2 1 1 2 3 4 5 14

Which does not mean at all that I recommend doing that. It can be done, and is useful sometimes, but we should avoid leading to obfuscation.

Replies are listed 'Best First'.
Re^5: Perl array declaring
by BillKSmith (Vicar) on Jun 02, 2013 at 03:51 UTC

    In Tobyink's example, there is only one global variable, $foo. Use of 'use warnings' would have warned about multiple declarations. Change every 'our' to 'my' and the warning changes to reflect new variables masking the old.

    In your case, you also have multiple variables with the same name, but in different scopes. As you said, this is sometimes useful, but you should not think of it as multiple declarations of the same variable.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1036510]
[Eily]: google tells me 1662 km ...
[LanX]: Nancy? Somewhere near Metz ...
[Eily]: must be km farenheit or something :P
[Eily]: wow, don't say that in Nancy LanX :P
[erix]: maybe you used the car routes, I used the walking routes
[Eily]: there's a rivalry between the two cities, so defining one in terms of the other might not be well received
[Eily]: erix well I did click on the walking icon
LanX giggles!
[LanX]: Eily I'm duing this constantly with people from rival cities ...MUCHO fun!
[Eily]: The best example of that is the TGV, they couldn't decide who would get it so it's in the middle of nowhere halfway between the two

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (13)
As of 2017-12-13 15:22 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (369 votes). Check out past polls.