typestar

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

  1. Assigning @beans to a scalar yields its length; wrapping the target in parens takes the first element instead.
  2. scalar(@beans) forces the count anywhere, even mid-list inside a print.
  3. A list assignment peels off $x and $y, then the greedy @rest swallows everything left.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Lists & context, step 10 of 27 in Language basics.

← Previous Next →