Our local state, my, my
May 08, 2015
Our local state, my, my
Your speaker for the evening
● Sawyer X● Github.com/xsawyerx● Blogs.perl.org/users/sawyer_x● #dancer @ irc.perl.org
Our local state, my, my
our, local, state, my, my
Perl variables, the easy part
● our is global● my is lexical
Easy part done!
What's a global variable?
● Perl code is divided to namespaces● 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”)● (globals are saved in typeglobs)
Global variables, examples
● our $name; # $main::name
● package My::Package;
our $name; # $My::Package::name
● say $Moose::VERSION;
Globals: done!
What's a lexical variable?
● Scoped variables● Variables that exist only in a scope!● Available scopes: block, file, eval● We define lexical variables with 'my' ● (they are saved in a lex pad)
Lexical variables, examples
● { my $exists_only_here }● { my $outer; { my $inner } }● foreach my $name (@names) {
say $name; # okay
}
say $name; # error
Lexical variables, pop quiz!
package Example;
my $exvar = 30;
package main;
say $exvar;
● Error or no error?
Lexical variables, pop quiz!
● 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; }
Lexicals: done!
What's a state variable?
● Lexical variables with a twist!● They don't get reinitialized● sub inc {
state $myvar = 0; # default value
return ++$myvar;
}
say inc($_) for 1 .. 10;
States: Done!
What's a local variable?
● Something that confuses people● But very simple, actually● Localizes an already existing variable● Used to temporarily override
variables instead of creating new ones● Useful with superglobals● Prevents fscking them up
Local variables, examples
● Slurping file content:
use autodie;
open my $fh, '<', $filename;
my $content = do { local $/; <$fh> };
close $fh;
Local variables, examples
● No output buffering for this scope:
local $| = 1;● Disabling warnings for a scope:
{
local $^W = 0;
# do something that would warn
}
Locals: done!
Questions?
Thank you!(yes, you can finally go home)