4.10
Scalar and List Context
Many Perl operations behave differently depending on the context in
which they are used. Perl has scalar context
and list context; both are listed in Example 4-8.
Example 4-8. Scalar context and list context
#!/usr/bin/perl -w
# Demonstration of "scalar context" and "list context"
@bases = ('A', 'C', 'G', 'T');
print "@bases\n";
$a = @bases;
print $a, "\n";
($a) = @bases;
print $a, "\n";
exit;
Here's the output of Example 4-8:
A C G T
4
A
First, Example 4-8 declares an array of the four
bases. Then the
assignment statement tries to assign
an array (which is a kind of list) to a scalar variable
$a:
$a = @bases;
In this kind of scalar
context
, an array
evaluates to the size of the array, that is, the number of elements
in the array. The scalar context is supplied by the scalar variable
on the left side of the statement.
Next, Example 4-8 tries to assign an array (to
repeat, a kind of list) to another list, in this case, having just
one variable, $a:
($a) = @bases;
In this kind of list
context
, an array evaluates to a list of its
elements. The list context is supplied by the list in parentheses on
the left side of the statement. If there aren't enough
variables on the left side to assign to, only part of the array gets
assigned to variables. This behavior of Perl pops up in many
situations; by design, many features of Perl behave differently
depending on whether they are in scalar or list context. See Appendix B for more about scalar and list content.
Now you've seen the use of strings and arrays to hold sequence
and file data, and learned the basic syntax of Perl, including
variables, assignment, printing, and reading files. You've
transcribed DNA to RNA and calculated the reverse complement of a
strand of DNA. By the end of Chapter 5,
you'll have covered the essentials
of Perl programming.