Perl Variables


Perl Variables

In this tutorial, we will learn about variables in Perl. We will cover the basics of declaring and using variables, including naming conventions.


What are Variables

Variables in Perl are used to store data values that can be manipulated during program execution. Perl is a dynamically typed language, meaning the data type of a variable can change at runtime.


Naming Variables

When naming variables in Perl, follow these conventions:

  • Variable names start with a special character: $ for scalars, @ for arrays, and % for hashes.
  • Following the special character, variable names must start with a letter or underscore (_).
  • Subsequent characters can include letters, digits, and underscores.
  • Avoid using reserved keywords as variable names.

Syntax

The syntax to declare variables in Perl is:

my $scalar = value;
my @array = (values);
my %hash = (key => value);


Variable storing Integer Value

  1. Declare an integer scalar variable named $num.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

Perl Program

# Declare and initialize an integer scalar variable
my $num = 10;
# Print the value of the variable
print "The value of num is: $num\n";

Output

The value of num is: 10


Variable storing String Value

  1. Declare a string scalar variable named $name.
  2. Assign the value 'John' to the variable.
  3. Print the value of the variable.

Perl Program

# Declare and initialize a string scalar variable
my $name = 'John';
# Print the value of the variable
print "The value of name is: $name\n";

Output

The value of name is: John


Variable storing Boolean Value

  1. Declare a boolean scalar variable named $isTrue.
  2. Assign the value 1 (true) to the variable.
  3. Print the value of the variable.

Perl Program

# Declare and initialize a boolean scalar variable
my $isTrue = 1;
# Print the value of the variable
print "The value of isTrue is: $isTrue\n";

Output

The value of isTrue is: 1