Chapter 6. Positionals
Your programming career is likely to be, at its heart, about moving and transforming ordered lists of some kind. Those might be to-do lists, shopping lists, lists of web pages, or just about anything else.
The broad term for such as list is Positional
. Not everything in this chapter
is strictly one of those; it’s okay to pretend that they are, though. The
language easily interchanges among many of the types you’ll see in this
chapter, and it’s sometimes important to keep them straight. Mind their
differences and their different uses to get exactly the behavior you
want.
This is the first chapter where you’ll experience the laziness of the language. Instead of computing things immediately as you specify them in your code, your program will remember it needs to do something. It then only does it if you later use it. This feature allows you to have infinite lists and sequences without actually creating them.
Constructing a List
A List
is an immutable series of zero or more items. The simplest List
is the empty list. You can construct one with no
arguments. The List
as a whole is one thingy and you
can store it in a scalar:
my $empty-list = List.new; put 'Elements: ', $empty-list.elems; # Elements: 0
The .elems
method returns the number of elements, which is 0
for the empty List
. This might seem like a trivial
result, but imagine those cases where you want to return no results: an
empty List
can be just as meaningful as a
nonempty one.
Instead of the call to .new
, you ...
Get Learning Perl 6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.