November 2017 Archives

Perl 5’s list-flattening and reference-taking design choices

Eevee:

Perl has the strange property that its data structures try very hard to spill their contents all over the place. Despite having dedicated syntax for arrays – @foo is an array variable, distinct from the single scalar variable $foo – it’s actually impossible to nest arrays.

my @foo = (1, 2, 3, 4);
my @bar = (@foo, @foo);
# @bar is now a flat list of eight items: 1, 2, 3, 4, 1, 2, 3, 4

The idea, I guess, is that an array is not one thing. It’s not a container, which happens to hold multiple things; it is multiple things. Anywhere that expects a single value, such as an array element, cannot contain an array, because an array fundamentally is not a single value.

And so we have “references”, which are a form of indirection, but also have the nice property that they’re single values.

This is a common thing for people to find weird about Perl. Really though it’s just a different default.

Perl’s reference-taking operator is simply dual with the splat operator in Ruby and recent Javascript.

About Aristotle

user-pic Waxing philosophical