Scalar and list context in Perl
The idea that makes Perl Perl: the same expression means two things depending on what receives it.
use strict;
use warnings;
my @beans = ("arabica", "robusta", "liberica");
my $count = @beans; # scalar context: the length
my ($first) = @beans; # list context: the first element
print "$count kinds, starting with $first\n";
print scalar(@beans), " again, forced with scalar()\n";
my ($x, $y, @rest) = (1, 2, 3, 4, 5);
print "x $x, y $y, rest @rest\n";
How it works
- Assigning
@beansto a scalar yields its length; wrapping the target in parens takes the first element instead. scalar(@beans)forces the count anywhere, even mid-list inside aprint.- A list assignment peels off
$xand$y, then the greedy@restswallows everything left.
Keywords and builtins used here
myprintscalaruse
The run, in numbers
- Lines
- 13
- Characters to type
- 364
- Tokens
- 75
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 64 seconds.
Step 1 of 3 in Lists & context, step 10 of 27 in Language basics.