Peter Bissmire

Communications & Language Services

Technical and general translations, French/German -> English

List context in Perl

This is an example of Larry Wall's linguistic approach to programming language design.
Consider what is happening when you write

@values=($value1, $value2, $value3);

On the right-hand side we have a list of values enclosed in brackets. In effect, writing the list in brackets creates a temporary array, the value of which is assigned to the array variable @values. So writing a comma separated list in brackets invokes list context. Indeed, writing anything in brackets invokes list context, provided that it makes sense. Thus, we can have:

$today = (Sun,Mon,Tue,Wed,​Thu,​Fri,​Sat)[(localtime)[6]];

The localtime function returns a list of numerical values. We place these in a temporary array by enclosing the function in brackets. Element number 6 is a number representing the day of the week. We enclose the whole in an outer pair of square brackets to use this number as the index of a temporary array containing day names.
$today thus becomes the name of the day of the week (in this case a 3-letter abbreviation).
Another example, this time with list context invoked on the left-hand side:

($sec,$min,$hour,$mday,​$mon,​$year,​$wday,$yday,$isdst) = localtime(time);

assigns each of the values returned by localtime to an individual variable. The last one indicates whether daylight saving time is in operation.

If we write:

($sec,$min,$hour,$mday,​$mon,​$year,​$wday,$yday,$isdst) = localtime(time);
$today = (Sun,Mon,Tue,Wed,Thu,​Fri,​Sat)[$wday];
$thismonth = (Jan,Feb,Mar,Apr,May,Jun,Jul,​Aug,​Sep,​Oct,Nov,Dec)[$mon];

then we are all set to output a complete time & date stamp in whatever format we wish.

This is analogous to the way that we manipulate simple grammatical constructs to build more complex sentences. If it makes sense, it's allowed — and once you have grasped the concept it saves a lot of brain power and tedious typing. In three statements, we have written what, in other programming languages, might require as many as 28 statements.