Chapter 11. Case Study: Data Structure Selection
At this point you have learned about Perl’s core data structures, and you have seen some of the algorithms that use them.
This chapter presents a case study with exercises that let you think about choosing data structures and practice using them.
But first, I would like to briefly introduce two conditional structures that have been left aside so far and provide a couple of new possibilities about subroutine signatures.
The Ternary Conditional Operator
Consider the following code that tests the value of a positive integer:
my $result; if $num < 10 { $result = "One digit"; } else { $result = "More than one digit"; } say $result;
This is quite simple, but a bit long. This can be rewritten in just one line of code:
say $num < 10 ?? "One digit" !! "More than one digit";
The operator is in two parts: the ??
and the !!
, which separate three expressions (hence the name “ternary operator”):
The condition to be evaluated (is
$num
less than 10?)The expression defining the value if the condition is true
The expression defining the value if the condition is false
This statement checks if $num
is less than 10 and, if true, prints “"One digit”; if the condition is false, it prints “More than one digit.”
This operator does not provide any new functionality; it just offers a more concise syntax.
It is possible to nest several ternary operators to examine successively multiple choices:
say $value < 10 ?? "One digit" !! $value < 100 ?? "Two digits" !! $value ...
Get Think 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.