What is the difference between “my” and “our” keywords in Perl?

1 Answers
Answered by suresh

Difference between "my" and "our" keywords in Perl

Difference between "my" and "our" keywords in Perl

In Perl, the "my" and "our" keywords are used to declare variables, but they have different scopes:

my keyword:

The "my" keyword declares a lexical variable that is only accessible within the block or file it was declared in. It has a limited scope and is not visible outside of the block it was declared in.

our keyword:

The "our" keyword, on the other hand, declares a package variable that is accessible outside of the block or file it was declared in. It has a global scope and can be accessed from anywhere in the package.

Using the "my" keyword is recommended for most variable declarations, as it helps avoid naming conflicts and keeps variables confined to a specific scope.

On the other hand, the "our" keyword is useful when you want to share variables across multiple subroutines or modules within the same package.

Answer for Question: What is the difference between “my” and “our” keywords in Perl?