In Perl, variables are declared using a sigil, which is a special character that specifies the type of value the variable holds. The three main types of variables in Perl are scalars, arrays, and hashes.
Scalars:
A scalar variable can hold a single value, such as a number, string, or reference. Scalar variables are declared using a dollar sign β$β as a sigil.
Hereβs an example of how to declare and use a scalar variable:
my $name = 'John';
print "Hello, $name!n";
Arrays:
An array variable holds an ordered list of values, which can be of any type. Array variables are declared using an at-sign β@β as a sigil.
Hereβs an example of how to declare and use an array variable:
my @numbers = (1, 2, 3, 4, 5);
print "The fourth element of the array is $numbers[3]n";
In Perl, array indices start at 0, so the fourth element of the array is indexed by β3β, not β4β.
Hashes:
A hash variable holds an unordered set of key-value pairs, where each key is unique. Hash variables are declared using a percent sign β%β as a sigil.
Hereβs an example of how to declare and use a hash variable:
my %person = (
name => 'John',
age => 35,
address => '123 Main St.',
);
print "$person{name} is $person{age} years old and lives at $person{address}n";
In this example, βnameβ, βageβ, and βaddressβ are keys, and ββJohnββ, β35β, and ββ123 Main St.ββ are values associated with those keys.
Assigning Values to Variables:
To assign a value to a variable in Perl, use the β=β operator. Here are some examples:
my $x = 10; # Assigns the integer 10 to $x
my $y = "Hello"; # Assigns the string "Hello" to $y
my @nums = (1, 2, 3); # Assigns an array of integers to @nums
my %info = ( # Assigns a hash of key-value pairs to %info
name => 'John',
age => 35,
address => '123 Main St.',
);
Accessing Values in Variables:
To access the value of a variable in Perl, use its name preceded by its sigil. Here are some examples:
my $x = 10;
my $y = "Hello";
print "$xn"; # Prints 10
print "$yn"; # Prints "Hello"
my @nums = (1, 2, 3);
print "$nums[1]n"; # Prints 2, which is the second element of the array
my %info = (
name => 'John',
age => 35,
address => '123 Main St.',
);
print "$info{name}n"; # Prints "John", which is the value associated with the key 'name'
In summary, scalars hold a single value, arrays hold an ordered list of values, and hashes hold an unordered set of key-value pairs. In Perl, the sigil of a variable specifies its type, and values can be assigned to and accessed from variables using their names preceded by their sigils.