Accessing Array Elements in Perl

PERLServer Side ProgrammingProgramming Scripts

When accessing individual elements from an array in Perl, you must prefix the variable with a dollar sign ($) and then append the element index within the square brackets after the name of the variable. For example −

Example

 Live Demo

#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
print "$days[0]\n";
print "$days[1]\n";
print "$days[2]\n";
print "$days[6]\n";
print "$days[-1]\n";
print "$days[-7]\n";

Output

This will produce the following result −

Mon
Tue
Wed
Sun
Sun
Mon

Array indices start from zero, so to access the first element you need to give 0 as indices. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. This means the following −

print $days[-1]; # outputs Sun
print $days[-7]; # outputs Mon
raja
Updated on 28-Nov-2019 09:36:15

Advertisements