Lesson 12 of 55
9 mins readPython Variable Scope: my, state & our
In Plain English
Perl offers three scoping declarators: `my` (lexical block scope), `state` (persistent lexical variable preserving value between calls), and `our` (package variable).
Deep Dive: How It Works
my: Lexical scope limited to the enclosing curly-brace block or file.
state: Initialized once and retains its value across multiple invocations (requires `use feature "state";`).
our: Declares an alias to a package global variable within the current lexical scope.
Core Rules to Remember

Always Prefer my: 99% of Perl variables should be declared with `my`.

state for Local Persistence: `state` provides static local persistence inside subroutines.
Live Interactive Example
Hit Run Code to see it liveLexical vs Block Scope
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: $inner_scoped ceased to exist when execution exited the curly brace block.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Declare Lexical Block Variable
Declare `my $session_id = "ABC-123";`
Print `"Active Session: $session_id\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.