Solved

Scope of 'our'

Posted on 2008-06-24
4
126 Views
Last Modified: 2010-03-05
Hi,

I thought in perl if you want to declare a global variable, you just use the 'our' keyword, like:

// my test script.pl:

a();
b();

sub a()
{
    our $g_age = 5;
}

sub b()
{
    print("Global age is: ", $g_age, "\n");
}


yeah but perl doesn't want to let that compile. What's the right way to do it? It doesn't make sense to be used like that anyway because $g_age wouldn't exist unless a() were executed anyway.

Thanks
0
Comment
Question by:DJ_AM_Juicebox
4 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 500 total points
ID: 21862551

our $g_age;

sub a()
{
   $g_age = 5;
}

sub b()
{
    print("Global age is: ", $g_age, "\n");
}
a();
b();
0
 

Author Comment

by:DJ_AM_Juicebox
ID: 21862586
Hi ozo,

Just as a test, I replaced the 'our' keyword with 'my', and it still works the same way, I guess because using 'my' at that scope is the same as global scope, at least in the context of a() and b(). What's the purpose of having the 'our' keyword then?

Thanks
0
 
LVL 48

Expert Comment

by:Tintin
ID: 21862600
$ perldoc -f our
       our EXPR
       our EXPR TYPE
       our EXPR : ATTRS
       our TYPE EXPR : ATTRS
               "our" associates a simple name with a package variable in the current package for use within the
               current scope.  When "use strict 'vars'" is in effect, "our" lets you use declared global vari-
               ables without qualifying them with package names, within the lexical scope of the "our" declara-
               tion.  In this way "our" differs from "use vars", which is package scoped.

               Unlike "my", which both allocates storage for a variable and associates a simple name with that
               storage for use within the current scope, "our" associates a simple name with a package variable
               in the current package, for use within the current scope.  In other words, "our" has the same
               scoping rules as "my", but does not necessarily create a variable.

               If more than one value is listed, the list must be placed in parentheses.

                   our $foo;
                   our($bar, $baz);

               An "our" declaration declares a global variable that will be visible across its entire lexical
               scope, even across package boundaries.  The package in which the variable is entered is deter-
               mined at the point of the declaration, not at the point of use.  This means the following behav-
               ior holds:

                   package Foo;
                   our $bar;           # declares $Foo::bar for rest of lexical scope
                   $bar = 20;

                   package Bar;
                   print $bar;         # prints 20, as it refers to $Foo::bar

               Multiple "our" declarations with the same name in the same lexical scope are allowed if they are
               in different packages.  If they happen to be in the same package, Perl will emit warnings if you
               have asked for them, just like multiple "my" declarations.  Unlike a second "my" declaration,
               which will bind the name to a fresh variable, a second "our" declaration in the same package, in
               the same scope, is merely redundant.

                   use warnings;
                   package Foo;
                   our $bar;           # declares $Foo::bar for rest of lexical scope
                   $bar = 20;

                   package Bar;
                   our $bar = 30;      # declares $Bar::bar for rest of lexical scope
                   print $bar;         # prints 30

                   our $bar;           # emits warning but has no other effect
                   print $bar;         # still prints 30

               An "our" declaration may also have a list of attributes associated with it.
               The exact semantics and interface of TYPE and ATTRS are still evolving.  TYPE is currently bound
               to the use of "fields" pragma, and attributes are handled using the "attributes" pragma, or
               starting from Perl 5.8.0 also via the "Attribute::Handlers" module.  See "Private Variables via
               my()" in perlsub for details, and fields, attributes, and Attribute::Handlers.

               The only currently recognized "our()" attribute is "unique" which indicates that a single copy
               of the global is to be used by all interpreters should the program happen to be running in a
               multi-interpreter environment. (The default behaviour would be for each interpreter to have its
               own copy of the global.)  Examples:

                   our @EXPORT : unique = qw(foo);
                   our %EXPORT_TAGS : unique = (bar => [qw(aa bb cc)]);
                   our $VERSION : unique = "1.00";

               Note that this attribute also has the effect of making the global readonly when the first new
               interpreter is cloned (for example, when the first new thread is created).

               Multi-interpreter environments can come to being either through the fork() emulation on Windows
               platforms, or by embedding perl in a multi-threaded application.  The "unique" attribute does
               nothing in all other environments.

               Warning: the current implementation of this attribute operates on the typeglob associated with
               the variable; this means that "our $x : unique" also has the effect of "our @x : unique; our %x
               : unique". This may be subject to change.
0
 
LVL 39

Expert Comment

by:Adam314
ID: 21869204
Variables declared with "our" are visible to other packages, while variables declared with "my" are not
our $test1;

my $test2;
 

$test1='this is test1';

$test2='this is test2';
 

print "main test1=$test1\n";

print "main test2=$test2\n";
 

SomeOtherPackage::PrintTest();
 

package SomeOtherPackage;
 

sub PrintTest {

	print "SomeOtherPackage test1=$main::test1\n";

	print "SomeOtherPackage test2=$main::test2\n";

}

Open in new window

0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now