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?
my is used for local variables, whereas our is used for global variables.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With