codescracker


perl

Perl Variables



« Previous Tutorial Next Tutorial »


Variables are basically the reserved memory locations to store values. Therefore, when you create a variable in your perl program, it means that you are reserving some space inside the memory.

Create a Variable in Perl

In perl, the variable declaration happens automatically when you assign a value to the variable. You must have to declare variable before use it. Here are some sample variable declarations in perl:

$name = "Devraj";
$age = 19;
$occupation = "Student";

Perl Scalar Variables

Here is an example uses scalar variables in perl:

#!/usr/bin/perl

$name = "Devraj";
$age = 19;
$occupation = "Student";

print("Name = $name\n");
print("Age = $age\n");
print("Occupation = $occupation");

Here is the sample output of the above perl program:

Name = Devraj
Age = 19
Occupation = Student

Perl Array Variables

Here is an example uses array variables in perl:

#!/usr/bin/perl
		
@ages_list = (19, 19, 18);
@names_list = ("Deepak", "Devraj", "Alok");

print("\$ages_list[0] = $ages_list[0]\n");
print "\$ages_list[1] = $ages_list[1]\n";
print "\$ages_list[2] = $ages_list[2]\n";
print "\$names_list[0] = $names_list[0]\n";
print "\$names_list[1] = $names_list[1]\n";
print "\$names_list[2] = $names_list[2]\n";

Note - Here we have used an escape (\) sign before dollar ($) sign to print it, otherwise, perl will understand it as a variable and then will print its value. Here is the sample output of the above perl program:

$ages_list[0] = 19
$ages_list[1] = 19
$ages_list[2] = 18
$names_list[0] = Deepak
$names_list[1] = Devraj
$names_list[2] = Alok

Perl Hash Variables

Here is an example uses hash variables in perl:

#!/usr/bin/perl

%names_ages_list = ('Deepak', 19, 'Devraj', 19, 'Alok', 18);

print("\$names_ages_list{'Deepak'} = $names_ages_list{'Deepak'}\n");
print("\$names_ages_list{'Devraj'} = $names_ages_list{'Devraj'}\n");
print("\$names_ages_list{'Alok'} = $names_ages_list{'Alok'}\n");

Here is the sample output of the above perl program:

$names_ages_list{'Deepak'} = 19
$names_ages_list{'Devraj'} = 19
$names_ages_list{'Alok'} = 18

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test