Accessing Array Elements
When accessing individual elements from an array, you must prefix the
variable with a dollar sign ($) and then append the element index within square
brackets after the name of the variable. For example:
#! /usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
print "$days[0]\t";
print "$days[1]\t";
print "$days[2]\t";
print "$days[6]\t";
print "$days[-1]\t";
print "$days[-7]\t";
This will produce following result:
Mon Tue Wed Sun Sun Mon
Array indices start from zero, so to access 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 that
print $days[-1]; # output Sun
print $days[-7]; # output Mon
No comments:
Post a Comment