191

I know what my is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our do?

How does our differ from my?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Nathan Fellman
  • 108,984
  • 95
  • 246
  • 308

12 Answers12

221

Great question: How does our differ from my and what does our do?

In Summary:

Available since Perl 5, my is a way to declare non-package variables, that are:

  • private
  • new
  • non-global
  • separate from any package, so that the variable cannot be accessed in the form of $package_name::variable.


On the other hand, our variables are package variables, and thus automatically:

  • global variables
  • definitely not private
  • not necessarily new
  • can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.


Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our.

For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block.

Cyclic3
  • 146
  • 2
  • 10
Fran Corpier
  • 2,751
  • 1
  • 14
  • 9
  • 2
    So how does our differ from local? – Nathan Fellman Aug 23 '09 at 13:51
  • 18
    @Nathan Fellman, `local` doesn't create variables. It doesn't relate to `my` and `our` at all. `local` temporarily backs up the value of variable and clears its current value. – ikegami Sep 21 '11 at 16:57
  • 2
    `our` variables are not package variables. They aren't globally-scoped, but lexically-scoped variables just like `my` variables. You can see that in the following program: `package Foo; our $x = 123; package Bar; say $x;`. If you want to "declare" a package variable, you need to use `use vars qw( $x );`. `our $x;` declares a lexically-scoped variable that is aliased to the same-named variable in the package in which the `our` was compiled. – ikegami Nov 20 '16 at 01:15
62

The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:

my variables are lexically scoped within a single block defined by {} or within the same file if not in {}s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.

our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.

Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.

StKiller
  • 6,955
  • 8
  • 39
  • 56
bubaker
  • 2,209
  • 1
  • 18
  • 13
  • +1 for "`my` variables are lexically scoped [...] within the same file if not in `{}`s". That was useful for me, thanks. – Georg Oct 01 '16 at 06:41
49

An example:

use strict;

for (1 .. 2){
    # Both variables are lexically scoped to the block.
    our ($o);  # Belongs to 'main' package.
    my  ($m);  # Does not belong to a package.

    # The variables differ with respect to newness.
    $o ++;
    $m ++;
    print __PACKAGE__, " >> o=$o m=$m\n";  # $m is always 1.

    # The package has changed, but we still have direct,
    # unqualified access to both variables, because the
    # lexical scope has not changed.
    package Fubb;
    print __PACKAGE__, " >> o=$o m=$m\n";
}

# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n";  # 2
print __PACKAGE__, " >> main::m=$main::m\n";  # Undefined.

# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";

# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
    use vars qw($uv);
    $uv ++;
}

# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";

# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";
FMc
  • 39,513
  • 12
  • 72
  • 131
11

Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.

The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.

daotoad
  • 25,670
  • 7
  • 54
  • 99
5

I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:

1. Definition or declaration?

local $var = 42;
print "var: $var\n";

The output is var: 42. However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:

use strict;
use warnings;

local $var = 42;
print "var: $var\n";

The second program will throw an error:

Global symbol "$var" requires explicit package name.

$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.

But why this won't fail?

use strict;
use warnings;

local $a = 42;
print "var: $a\n";

The output is: var: 42.

That's because $a, as well as $b, is a global variable pre-defined in Perl. Remember the sort function?

2. Lexical or global?

I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: it just corresponds to auto and external variables in C. But there're small differences:

In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:

int global;

int main(void) {
    int local;
}

While in Perl, things are subtle:

sub main {
    $var = 42;
}

&main;

print "var: $var\n";

The output is var: 42. $var is a global variable even if it's defined in a function block! Actually in Perl, any variable is declared as global by default.

The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Logan Ding
  • 1,721
  • 1
  • 10
  • 23
  • More on ["remembering [$a and $b in] sort" here](http://stackoverflow.com/a/26128328/1028230). Perl never ceases to, um, astound me. – ruffin Feb 10 '15 at 19:47
5

my is used for local variables, whereas our is used for global variables.

More reading over at Variable Scoping in Perl: the basics.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
ismail
  • 41,546
  • 8
  • 79
  • 92
  • 16
    Be careful tossing around the words local and global. The proper terms are lexical and package. You can't create true global variables in Perl, but some already exist like $_, and local refers to package variables with localized values (created by local), not to lexical variables (created with my). – Chas. Owens May 11 '09 at 00:16
  • `${^Potato}` is global. It refers to the same variable regardless of where you use it. – Mark Dominus Oct 07 '13 at 14:02
4

The perldoc has a good definition of our.

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.

Chas. Owens
  • 61,688
  • 16
  • 123
  • 216
Ólafur Waage
  • 64,767
  • 17
  • 135
  • 193
2

This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.

#!/usr/bin/perl

our $foo = "BAR";

print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";

Output:

BAR
BAZ

This won't work if you change 'our' to 'my'.

Misha Gale
  • 97
  • 1
  • 8
  • 1
    Not so. $foo ${foo} ${'foo'} ${"foo"} all work the same for variable assignment or dereferencing. Swapping the *our* in the above example for *my* does work. What you probably experienced was trying to dereference $foo as a package variable, such as $main::foo or $::foo which will only work for package globals, such as those defined with *our*. – Cosmicnet Oct 21 '14 at 14:08
  • Just retested using v5.20, and it definitely doesn't give the same output with my (it prints BAR twice.) – Misha Gale Oct 21 '14 at 17:50
  • 1
    My test (on windows): `perl -e "my $foo = 'bar'; print $foo; ${foo} = 'baz'; pr int $foo"` output: `barbaz` `perl -e "my $foo = 'bar'; print $foo; ${"foo"} = 'baz'; print $foo"` output: `barbaz` `perl -e "my $foo = 'bar'; print $foo; ${\"foo\"} = 'baz'; print $foo"` output: `barbar` So in my testing I'd fallen into the same trap. ${foo} is the same as $foo, the brackets are useful when interpolating. ${"foo"} is actually a look up to $main::{} which is the main symbol table, as such only contains package scoped variables. – Cosmicnet Nov 22 '14 at 13:44
  • 1
    ${"main::foo"}, ${"::foo"}, and $main::foo are the same as ${"foo"}. The shorthand is package sensitive `perl -e "package test; our $foo = 'bar'; print $foo; ${\"foo\"} = 'baz'; print $foo"` works, as in this context ${"foo"} is now equal to ${"test::foo"}. [Of Symbol Tables and Globs](http://www.perlmonks.org/?node_id=211441) has some information on it, as does the Advanced Perl programming book. Sorry for my previous mistake. – Cosmicnet Nov 22 '14 at 13:57
0
print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";

package Changed;

{
        my $test = 10;
        my $test1 = 11;
        print "trying to print local vars from a closed block: $test, $test1\n";
}

&Check_global;

sub Check_global {
        print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package:     $test\n";
print "trying to print local var outside the block $test1\n";

Will Output this:

package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block 

In case using "use strict" will get this failure while attempting to run the script:

Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.
Nathan Fellman
  • 108,984
  • 95
  • 246
  • 308
  • Please provide some kind of explanation. Dumping code like this is rarely considered appropriate. – Scott Solmer Sep 05 '14 at 12:29
  • in simple words: Our (as the name sais) is a variable decliration to use that variable from any place in the script (function, block etc ...), every variable by default (in case not declared) belong to "main" package, our variable still can be used even after decliration of another package in the script. "my" variable in case declared in a block or function, can be used in that block/function only. in case "my" variable was declared not closed in a block, it can be used any where in the scriot, in a closed block as well or in a function as "our" variable, but can't used in case package changed – Lavi Buchnik Sep 06 '14 at 20:08
  • My script above shows that by default we are in the "main" package, then the script print an "our" variable from "main" package (not closed in a block), then we declare two "my" variables in a function and print them from that function. then we print an "our" variable from another function to show it can be used in a function. then we changing the package to "changed" (not "main" no more), and we print again the "our" variable successfully. then trying to print a "my" variable outside of the function and failed. the script just showing the difference between "our" and "my" usage. – Lavi Buchnik Sep 06 '14 at 20:13
0

Just try to use the following program :

#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;


print "$a \n";
print "$b \n";
}

package b;

#my $b = 200;
#our $a = 20 ;

print "in package b value of  my b $a::b \n";
print "in package b value of our a  $a::a \n";
Yugdev
  • 1
  • This explains the difference between my and our. The my variable goes out of scope outside the curly braces and is garbage collected but the our variable still lives. – Yugdev Nov 05 '15 at 14:03
-1
#!/usr/bin/perl -l

use strict;

# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'

our $lol = eval {$lol} || 'lol' ;

print $lol;
xoid
  • 988
  • 1
  • 8
  • 18
-1

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources: