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;
    }

SEE ALSO

http://design.perl6.org/S04.html#Conditional_statements

[/perl-5-to-6] Permanent link