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

Re: Re: Perl keywords for declaring variables: my, our and local???

by demerphq (Chancellor)
on Mar 23, 2003 at 10:07 UTC ( #245261=note: print w/ replies, xml ) Need Help??


in reply to Re: Perl keywords for declaring variables: my, our and local???
in thread Perl keywords for declaring variables: my, our and local???

our is a lexically scoped alias for a global variable. Will create the global if it didn't exist already

This is a little misleading. Global variables are created on first use regardless. And when you say alias I can see what you mean but wouldnt use that term personally. strict complains if it sees a symbol that isn't a fully qualified package variable (aka global) or if it hasn't been declared by my or it doesnt meet a handful of esoteric exceptions (like $_ and $a $b). our is the workaround to tell strict that in a given lexical scope a given symbol defaults to meaning the package variable and not to worry if it hasnt been declared already as a lexical. It means you don't have to fully qualify your globals, which also means that strict can catch your typos. An alternate means to accomplish this goal is to use vars qw(); which I personally prefer.

By default any global variables you create automatically populate the "main" symbol table, %main::. With a package declaration you could change which symbol table you are populating when you declare unqualified variables.

Again this is correct but IMO a little muddled. Unqualified globals (with certain exceptians left aside) are presumed to refer to the package in which they are used. If no package declaration is provided then it defaults to 'main'. To fully qualify something to main you need not write $main::foo but rather $::foo. But again declaration does not directly mean creation or population. It does indirectly as it potentially means "first use" but its the "first use" rule that creates the var and not the declaration. Ie:

package Foo; use strict; use vars qw/$DEBUG/; our $DEBUG; $Foo::DEBUG=1;

neither "declaration" is necessary in this case at all.

Personally I like to think of it this way: "our and use vars advise strict not to complain about unqualified globals.", "my declares a new lexical variable" and "local creates a new dynamic scope for a variable"


---
demerphq



Comment on Re: Re: Perl keywords for declaring variables: my, our and local???
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-07-22 10:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (109 votes), past polls