Categories
Posts in this category
- Introduction
- Strings, Arrays, Hashes;
- Types
- Basic Control Structures
- Subroutines and Signatures
- Objects and Classes
- Contexts
- Regexes (also called "rules")
- Junctions
- Comparing and Matching
- Containers and Values
- Where we are now - an update
- Changes to Perl 5 Operators
- Laziness
- Custom Operators
- The MAIN sub
- Twigils
- Enums
- Unicode
- Scoping
- Regexes strike back
- A grammar for (pseudo) XML
- Subset Types
- The State of the implementations
- Quoting and Parsing
- The Reduction Meta Operator
- The Cross Meta Operator
- Exceptions and control exceptions
- Common Perl 6 data processing idioms
- Currying
Sun, 21 Sep 2008
Basic Control Structures
Permanent link
NAME
"Perl 5 to 6" Lesson 03 - Basic Control Structures
LAST UPDATE
2015-02-25
SYNOPSIS
if $percent > 100 { say "weird mathematics"; } for 1..3 { # using $_ as loop variable say 2 * $_; } for 1..3 -> $x { # with explicit loop variable say 2 * $x; } while $stuff.is_wrong { $stuff.try_to_make_right; } die "Access denied" unless $password eq "Secret";
DESCRIPTION
Most Perl 5 control structures are quite similar in Perl 6. The biggest visual difference is that you don't need a pair of parentheses after if
, while
, for
etc.
In fact you are discouraged from using parenthesis around conditions. The reason is that any identifier followed immediately (ie. without whitespace) by an opening parenthesis is parsed as a subroutine call, so if($x < 3)
tries to call a function named if
. While a space after the if
fixes that, it is safer to just omit the parens.
Branches
if
is mostly unchanged, you can still add elsif
and else
branches. unless
is still there, but no else
branch is allowed after unless
.
my $sheep = 42; if $sheep == 0 { say "How boring"; } elsif $sheep == 1 { say "One lonely sheep"; } else { say "A herd, how lovely!"; }
You can also use if
and unless
as a statement modifier, i.e. after a statement:
say "you won" if $answer == 42;
Loops
You can manipulate loops with next
and last
just like in Perl 5.
The for
-Loop is now only used to iterate over lists. By default the topic variable $_
is used, unless an explicit loop variable is given.
for 1..10 -> $x { say $x; }
The -> $x { ... }
thing is called a "pointy block" and is something like an anonymous sub, or a lambda in lisp.
You can also use more than one loop variable:
for 0..5 -> $even, $odd { say "Even: $even \t Odd: $odd"; }
This is also a good way to iterate over hashes:
my %h = a => 1, b => 2, c => 3; for %h.kv -> $key, $value { say "$key: $value"; }
The C-style for-loop is now called loop
(and the only looping construct that requires parentheses):
loop (my $x = 2; $x < 100; $x = $x**2) { say $x; }