Tuesday, 11 March 2014

Special Variable



The $[ Special Variable

So far you have seen simple variable we defined in our programs and used them to store and print scalar and array values. Perl provides numerous special variables which have their predefined meaning.
We have a special variable which is written as $[. This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable:
#! /usr/bin/perl
 
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
 
# Let's reset first index of all the arrays.
$[ = 1;
 
print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";
This will produce following result:
Foods: pizza steak chicken burgers
Food at @foods[1]: pizza
Food at @foods[2]: steak

No comments: