our is global
my is lexical
we use 'package to declare them.
'main' is the default namespace
globals are package variables
variables relating to that namespace
(not the same as superglobals)
our $name ; # $main::name
package My::Package;
our $name;#$My::Package::name
say $Moose::VERSION;
What is a lexical variable?
Scoped variables
Variables that exist only in a scope!
Available scopes:block, file ,eval
We defind lexical variables with 'my'
(they are saved in a lex pad)
Lexical variable , examples:
{my $exists_only_here}
{my $outer;{my $inner;}}
foreach my $name(@names){
say $name;
}
say $name; #ERROR
Lexical variables,quiz:
package Example;
my $exvar =30;
package main;
print $exvar;#Display output 30
Answer:
NO ERROR!
my is lexical
package is a namespace, not a scope
The scope here is the "file scope"
Here is the correct way to do it:
{package Example;my $exvar;}
What is a state variable?
Lexical variables with a twist!
The don't get reinitialized
sub inc{
state $myvar =0;#default value
return ++$myvar;
}
沒有留言:
張貼留言