Some Notes about Perl Array Contexts



next up previous
Next: Subroutines and Packages Up: Previous: Use of the

Some Notes about Perl Array Contexts

In C, every expression yields some kind of value. That value can be used as input to another routine without having to store it in a temporary variable. Thus, you can do things like chdir(getenv("HOME")).

In Perl, many routines and contexts yield arrays. These resultant arrays can be passed to other routines, iterated over, and subscripted. This eliminates the need for many temporary variables.

Here are a few examples. In this first case, we use the sort routine. This routine takes an array as a parameter and passes back a sorted version of the same array.

@names = ("bill","hillary","chelsea","socks");
@sorted = sort @names;
foreach $name (@sorted)
{ print $name,"\n"; }

In fact, one can iterate directly over the output from sort.

foreach $name (sort @names)
{ print $name,"\n"; }

This example shows that we can even put a subscript on an array context.

$name = (getpwuid($<))[6];
print "my name is ",$name,"\n";

The function getpwuid returns an array. We want the ``real name'' (or GECOS) field from the passwd entry so we put a subscript of [6] on the array context and put the result in $name.