1. Perl
  2. Syntax
  3. here

my - lexical variable declaration

You can declare a lexical variable using my.

# Declaration of lexical variables
my $num;
my @nums;
my %scores;

A lexical variable in Perl is the same concept as a local variable in C language.

Perl has the keyword local, but it doesn't actually create a local variable. The local keyword save temporarily and restore a package variable.

the lexical variable declaration by my is a feature added in Perl 5.6. This is the samae as the local variable in other languages, but because the keyword local already exists, it may have been named "lexical variable" so as not to be confusing.

Think of a lexical variable in Perl as a local variable in other languages.

Variable declaration

The variable declaration declares that the program uses variable from now.

# Declaration of a scalar variable
my $num;

In addition to a scalar variable, you can also declare a array variable and a hash variable.

# Declaration of a array variable
my @nums;

# Declaration of a hash variable
my %score;

Variable initialization

A variable initialization can be written at the same time as the variable declaration.

# Initialization of a scalar variable
my $num = 3;

# Initialization of a array variable
my @nums = (1, 2, 3);

# Initialization of a hash variable
my %score = (math => 80, english => 70);

If initialization is not written, undefined value is assigned for a scalar variable. For a array variable and a hash variable, empty list is assigned.

What is a lexical variable?

What is a lexical variable? A lexical variable is a variable that has a lexical scope.

Lexical variable have reached the end of their life and are freed from memory at the end of scope.

# Start of scope
  my $num = 2;
# "$num" is not available here.

See below for the detailed explanation of the lexical scope.

Cooperation with strict module

If you use the strict module and the variable declaration by my together, you will get a compile error if you try to use the variable without the variable declaration.

use strict;

my $num = 1;

# Compile error occurs because the variable name is incorrect
print $nam;

You can quickly find unused variables using the strict module.

See below for the detailed explanation of the strict module.

Difference in variable declarations by "my", "our" and "local"

There are three Perl variable declarations: "my", "our", and "local".

The simple difference is that "my" declares a "a lexical variable", "our" declares a "a package variable", and "local" declares a package variable and saves the value until the end of scope.

Avoid using "our" or "local" as much as possible. In modern Perl, you can write easy-to-read programs using only lexical variable declarations by "my".

See below for additional explanations for our and local.

Related Informatrion