Types of Scope I

Learn about the scope and its types in Perl.

We'll cover the following

Everything with a name in Perl (a variable, a function, a filehandle, a class) has a scope. This scope governs the lifespan and visibility of these entities. Scoping helps enforce encapsulation—keeping related concepts together and preventing their details from leaking.

Lexical scope

Lexical scope is the scope apparent to the readers of a program. Any block delimited by curly braces creates a new scope: a bare block, the block of a loop construct, the block of a subdeclaration, an eval block, a package block, or any other nonquoting block. The Perl compiler resolves this scope during compilation.

Lexical scope describes the visibility of variables declared with my—that we refer to as lexical variables. A lexical variable declared in one scope is visible in that scope and any scopes nested within it but is invisible to sibling or outer scopes:

Get hands-on with 1200+ tech skills courses.