Tuesday, March 31, 2015

Merging Arrays

The $[ Special Variable

We have a speciall 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

Merging Arrays

Because an array is just a comma-separated sequence of values, you can combine them together as shown below:
#!/usr/bin/perl

@numbers = (1,3,(4,5,6));

print "numbers = @numbers\n";
This will produce following result:
numbers = 1 3 4 5 6
The embedded arrays just become part of the main array as shown below:
#!/usr/bin/perl

@odd = (1,3,5);
@even = (2, 4, 6);

@numbers = (@odd, @even);

print "numbers = @numbers\n";
This will produce following result:
numbers = 1 3 5 2 4 6

Selecting Elements from Lists

The list notation is identical to that for arrays - you can extract an element from an array by appending square brackets to the list and giving one or more indices:
#!/usr/bin/perl

$var = (5,4,3,2,1)[4];

print "value of var = $var\n"
This will produce following result:
value of var = 1
Similarly, we can extract slices, although without the requirement for a leading @ character:
#!/usr/bin/perl

@list = (5,4,3,2,1)[1..3];

print "Value of list = @list\n";
This will produce following result:
Value of list = 4 3 2