Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between my and our ? (declared in the same file)

Tags:

perl

Before writing this program,I thought that our is a package scope variable and my is a file scope variable.But,After did that program,I am get confused.

My program is,

#!/usr/bin/perl

use strict;
use warnings;

package one; 
our $val = "sat";
my $new = "hello";
print "ONE:val =>$val \n";
print "ONE:new =>$new \n\n";

package two;
print "TWO:val =>$val \n";
print "TWO:new =>$new \n";

which outputs

ONE:val =>sat 
ONE:new =>hello 

TWO:val =>sat 
TWO:new =>hello 

So,what is the difference between my and our.Whether the both are the same or it having any difference?

like image 666
sat Avatar asked May 23 '12 12:05

sat


People also ask

What is difference between my and our?

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

What is the difference between my and local in Perl?

Quick summary: 'my' creates a new variable, 'local' temporarily amends the value of a variable. ie, 'local' temporarily changes the value of the variable, but only within the scope it exists in.

What does our mean in Perl?

Our Keyword in Perl: “our” keyword only creates an alias to an existing package variable of the same name. our keyword allows to use a package variable without qualifying it with the package name, but only within the lexical scope of the “our” declaration.

What is a lexical scope?

Understanding lexical scoping In a programming language, an item's lexical scope is the place in which it was created. The scope of the variable is determined by the program's textual (lexical) structure. Variables can be declared within a specific scope and are only accessible within that region.


1 Answers

As you see, both my and our have lexical effect.

my creates a lexically scoped variable.

our creates a lexically scoped alias to a package variable.

Just because you say package in no fashion changes the lexical scope, so your $val is still an alias to $one::val even after having seen the package two statement.

If you don’t see a close curly, you haven’t finished your scope. (Or EOF or end of string in a string eval).

like image 70
tchrist Avatar answered Oct 02 '22 14:10

tchrist