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

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"


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2018-05-23 07:59 GMT
Find Nodes?
    Voting Booth?