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
Sun, 21 Sep 2008
Basic Control Structures
Permanent link
NAME
"Perl 5 to 6" Lesson 03 - Basic Control Structures
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 parenthesis after if, while, for etc.
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.
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 statements:
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 standard 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 how you 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:
loop (my $x = 1; $x < 100; $x = $x**2) {
say $x;
}