Perl Access Modifiers

In Perl, access modifiers such as my, local, and our are used to control the visibility and scope of variables. Here’s an overview of how each one works:

1) my: Lexical Variables (Private to the Block)

 

The my keyword is used to declare lexical variables, which are private to the block in which they are declared. These variables are confined to the scope of the block and are destroyed once the block is exited.

 

 

In this example, the variable $age is visible inside and outside the block, because it was declared at the program’s beginning.

 

2) local: Temporarily Masking a Variable

 

The local keyword is used to temporarily override the value of a global variable within a block. It doesn’t change the original value of the variable permanently; instead, it masks the variable temporarily within the block’s scope.

 

 

In this example, the variable $var is temporarily changed to 3 inside the block due to local, but the original value (5) remains unchanged outside the block.

 

3) our: Package Variables (Global Scope)

 

The our keyword is used to declare variables that are global to the entire package. These variables can be accessed across different blocks or even scripts that use the package where the variable is declared. The scope of an our variable extends across the entire package or program, making it accessible globally.

Example: Using our:

 

In this example, the variable $greeting is declared using our and is accessible both inside the main program and inside the subroutine print_greeting.

Summary of Access Modifiers:

 

my: Used for lexical variables. The variable is scoped to the block in which it is declared. It’s private to the block and can’t be accessed outside.
local: Used to temporarily override global variables within a block. The change is temporary and only affects the block’s scope.
our: Used for global package variables. These variables are accessible throughout the package, and in scripts that use the package.
Let me know if you’d like to explore any of these concepts further!

 

80 thoughts on “Perl Access Modifiers”

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top