Pages

Slicing arrays

Perl arrays are so flexible that someone (with that sort of twisted mind) could say it is quite fun to work with them.

Say that you have this definition of an array:
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
And you want to print just some of its elements. Here is a very compact way to say "print the fourth, fifth element, and then all the elements from the eigth to nineth, each of them separated by a blank":
print "@months[3, 4, 7 .. 9]";
The array is in a double quoted string exactely to have it interpolated, that in this case means a blank inserted between each adiacent couple of elements.

Consider another array, and assume this one keep the sale numbers for the past year:
my @sales = (41, 32, 53, 34, 85, 36, 27, 98, 39, 60, 31, 42);
We can easily slice both arrays, months and sales, to show partial results:

print "Summer sales: ";
print "@months[5 .. 7] - @sales[5 .. 7]\n";

And we can use slices to manipulate values in an array. Here, for instance, we swap the values in two months:

print "Swapping Jun and Aug: ";
@sales[5, 7] = @sales[7, 5];
print "@months[5 .. 7] - @sales[5 .. 7]\n";

Chapter 3 of Beginning Perl by Simon Cozens is about arrays and associative arrays (hashes).

No comments:

Post a Comment