Herbert Breunung > Perl6-Doc > Synopsis_04


Annotate this POD


Open  0
View/Report Bugs


Synopsis_04 - Blocks and Statements


Larry Wall <larry@wall.org>


  Maintainer: Larry Wall <larry@wall.org>
  Date: 19 Aug 2004
  Last Modified: 8 Feb 2008
  Number: 4
  Version: 64


The Relationship of Blocks and Declarations ^

Every block is a closure. (That is, in the abstract, they're all anonymous subroutines that take a snapshot of their lexical scope.) How a block is invoked and how its results are used are matters of context, but closures all work the same on the inside.

Blocks are delimited by curlies, or by the beginning and end of the current compilation unit (either the current file or the current eval string). Unlike in Perl�5, there are (by policy) no implicit blocks around standard control structures. (You could write a macro that violates this, but resist the urge.) Variables that mediate between an outer statement and an inner block (such as loop variables) should generally be declared as formal parameters to that block. There are three ways to declare formal parameters to a closure.


A bare closure without placeholder arguments that uses $_ (either explicitly or implicitly) is treated as though $_ were a formal parameter:

    $func = { .print if $_ };   # Same as: $func = -> $_ { .print if $_ };



    my $x = $x;


    my $x = $OUTER::x;


    my $x = OUTER::<$x>;



    my $x;
    my $x;


    my proto $x;


As in Perl�5, "our $foo" introduces a lexically scoped alias for a variable in the current package.

The new constant declarator introduces a lexically scoped name for a compile-time constant, either a variable or a 0-ary sub, which may be initialized with a pseudo-assignment:

    constant Num $pi = 3;
    constant Num π  = atan(2,2) * 4;

The initializing expression is evaluated at BEGIN time.


Perl�5's "local" function has been renamed to temp to better reflect what it does. There is also a let function that sets a hypothetical value. It works exactly like temp, except that the value will be restored only if the current block exits unsuccessfully. (See Definition of Success below for more.) temp and let temporize or hypotheticalize the value or the variable depending on whether you do assignment or binding. One other difference from Perl�5 is that the default is not to undefine a variable. So

    temp $x;

causes $x to start with its current value. Use

    temp undefine $x;

to get the Perl�5 behavior.


The Relationship of Blocks and Statements ^

The return value of a block is the value of its final statement. (This is subtly different from Perl�5's behavior, which was to return the value of the last expression evaluated, even if that expression was just a conditional.)

Statement-ending blocks ^


    my $x = sub { 3 }
    my $x = sub { 3 };

End-of-statement cannot occur within a bracketed expression, so this still works:

    my $x = [
        sub { 3 },  # this comma is not optional
        sub { 3 }   # the statement won't terminate here 

However, a hash composer may never occur at the end of a line. If the parser sees anything that looks like a hash composer at the end of the line, it fails with "closing hash curly may not terminate line" or some such.

    my $hash = {
        2 => { 6 => 7, 8 => 9 }   # ERROR



But these two are valid:

    sub f { 3 }; sub g { 3 };



Conditional statements ^

The if and unless statements work much as they do in Perl�5. However, you may omit the parentheses on the conditional:

    if $foo == 123 {
    elsif $foo == 321 {
    else {

If the final statement is a conditional which does not execute any branch, the return value is undef in item context and () in list context.

The unless statement does not allow an elsif or else in Perl�6.


    else          -> $b { say $b }


An explicit placeholder may also be used:

    if blahblah() { return $^it }


    if .haste { .waste }

(Contrast with a non-conditional statement such as:

    for .haste { .waste }


Conditional statement modifiers work as in Perl�5. So do the implicit conditionals implied by short-circuit operators. Note though that the first expression within parens or brackets is parsed as a statement, so you can say:


and that is equivalent to:


Loop statements ^

Looping statement modifiers are the same as in Perl�5 except that, for ease of writing list comprehensions, a looping statement modifier is allowed to contain a single conditional statement modifier:


Loop modifiers next, last, and redo also work as in Perl�5. However, the labelled forms use method call syntax: LABEL.next, etc. The .next and .last methods take an optional argument giving the final value of that loop iteration. So the old next LINE syntax is still allowed but is really short for next LINE: using indirect object syntax. Any block object can be used, not just labels, so to return a value from this iteration of the current block you can say:




The value of a loop statement is the list of values from each iteration. Iterations that return a null list (such as by calling next with no extra return arguments) interpolate no values in the resulting list. (This list is actually a two-dimensional list of Captures (a "slice") with dimensional boundaries at each iteration. Normal list context ignores these boundaries and flattens the list. Slice context turns the captures into subarrays, so an iteration returning a null list does show up as a null subarray when viewed as a slice.)



The while and until statements

The while and until statements work as in Perl�5, except that you may leave out the parentheses around the conditional:

    while $bar < 100 {


    while something() -> $thing {

    while something() -> { ... $^thing ... }


The repeat statement

Unlike in Perl�5, applying a statement modifier to a do block is specifically disallowed:

    do {
    } while $x < 10;    # ILLEGAL


    repeat {
    } while $x < 10;

or equivalently:

    repeat {
    } until $x >= 10;


    while $x < 10;


    repeat while $x < 10

or equivalently:

    repeat until $x >= 10


    repeat -> $thing {
    } while something();


    repeat while something() -> $thing {


The general loop statement




    loop {...}

is equivalent to the Cish idiom:

    loop (;;) {...}

The for statement

There is no foreach statement any more. It's always spelled for in Perl�6, so it always takes a list as an argument:

    for @foo { .print }


    for @foo -> $item { print $item }







in Perl�6 you should use a for (plus a unary = "iterate the iterator" operator) instead:

    for =$*IN -> $line {...}


    while =$*IN -> $line {...}

Note also that Perl�5's special rule causing

    while (<>) {...}

to automatically assign to $_ is not carried over to Perl�6. That should now be written:

    for =<> {...}

which is short for

    for =$*ARGS {...}





This is equivalent to



    for @foo {...}

is actually short for:


so you can modify the current list element in that case.

When used as statement modifiers, for and given use a private instance of $_ for the left side of the statement. The outer $_ can be referred to as $OUTER::_. (And yes, this implies that the compiler may have to retroactively change the binding of <$_> on the left side. But it's what people expect of a pronoun like "it".)

The do-once loop

In Perl�5, a bare block is deemed to be a do-once loop. In Perl�6, the bare block is not a do-once. Instead do {...} is the do-once loop (which is another reason you can't put a statement modifier on it; use repeat for a test-at-the-end loop).



This construct only allows you to attach a single statement to the end of an expression. If you want to continue the expression after the statement, or if you want to attach multiple statements. you must either use the curly form or surround the entire expression in brackets of some sort:

    @primes = (do (do $_ if .prime) for 1..100);

Since a bare expression may be used as a statement, you may use do on an expression, but its only effect is to function as an unmatched left parenthesis, much like the $ operator in Haskell. That is, precedence decisions do not cross a do boundary, and the missing "right paren" is assumed at the next statement terminator or unmatched bracket. A do is assumed immediately after any opening bracket, so the above can in fact be written:

    @primes = (($_ if .prime) for 1..100);

This basically gives us list comprehensions as rvalue expressions:

    (for 1..100 { $_ if .prime}).say

Since do is defined as going in front of a statement, it follows that it can always be followed by a statement label. This is particularly useful for the do-once block, since it is offically a loop and can take therefore loop control statements.

Although a bare block is no longer a do-once loop, it still executes immediately as in Perl�5, as if it were immediately dereferenced with a .() postfix, so within such a block CALLER:: refers to the scope surrounding the block. If you wish to return a closure from a function, you must use an explicit prefix such as return or sub or ->. (Use of a placeholder parameter is deemed insufficiently explicit because it's not out front where it can be seen. You can, of course, use a placeholder parameter if you also use return.)



or equivalently, using placeholders:


The gather statement

A variant of do is gather. Like do, it is followed by a statement or block, and executes it once. Unlike do, it evaluates the statement or block in void context; its return value is instead specified by calling the take list prefix operator one or more times within the dynamic scope of the gather. The take function's signature is like that of return; it merely captures the Capture of its argments without imposing any additional constraints (in the absence of context propagation by the optimizer). The value returned by the take to its own context is that same Capture object (which is ignored when the take is in void context). Regardless of the take's context, the Capture object is also added to the list of values being gathered, which is returned by the gather in the form of a lazy slice, with each slice element corresponding to one take capture. (A list of Captures is lazily flattened in normal list context, but you may "unflatten" it again with a @@() contextualizer.)

Because gather evaluates its block or statement in void context, this typically causes the take function to be evaluated in void context. However, a take function that is not in void context gathers its arguments en passant and also returns them unchanged. This makes it easy to keep track of what you last "took":

    my @uniq = gather for @list {
        state $previous = take $_;
        next if $_ === $previous;
        $previous = take $_;


    my @y;
    @x = gather for 1..2 {          # @() context for list of captures
        my $x = take $_, $_ * 10;   # $() context for individual capture
        push @y, $x;
    # @x returns 1,10,2,20
    # @y returns [1,10],[2,20]

Likewise, we can just remember the gather's result by binding and later coerce it:

    $c := gather for 1..2 {
        take $_, $_ * 10;
    # @$c returns 1,10,2,20
    # @@$c returns [1,10],[2,20]
    # $$c returns [[1,10],[2,20]]

Note that the take itself is in void context in this example because the for loop is in void context.


If any function called as part of a take list asks what its context is, it will be told it was called in list context regardless of the eventual binding of the returned Capture. If that is not the desired behavior you must coerce the call to an appropriate context. In any event, such a function is called only once at the time the Capture object is generated, not when it is bound (which could happen more than once).

Other do-like forms

Other similar Code-only forms may also take bare statements, including try, contend, async, and lazy. These constructs establish a dynamic scope without necessarily establishing a lexical scope. (You can always establish a lexical scope explicitly by using the block form of argument.) As statement introducers, all these keywords must be followed by whitespace. You can say something like try({...}), but then you are calling it using function call syntax instead, in which case the Code argument must be a block. For purposes of flow control, none of these forms are considered loops, but they may easily be applied to a normal loop.

Switch statements ^


    given EXPR {
        when EXPR { ... }
        when EXPR { ... }
        default { ... }



The default case:

    default {...}

is exactly equivalent to

    when * {...}



You can explicitly break out of a when block (and its surrounding topicalizer block) early using the break verb. More precisely, it leaves the innermost block outside the when that uses $_ as one of its formal parameters, either explicitly or implicitly. It does this essentially by going to the end of the block and returning normally from that block. In other words, a break (either implicit or explicit) is assumed to indicate success, not failure.

You can explicitly leave a when block and go to the next statement following the when by using continue. (Note that, unlike C's idea of "falling through", subsequent when conditions are evaluated. To jump into the next when block without testing its condition, you must use a goto.)

If you have a switch that is the main block of a for loop, and you break out of the switch either implicitly or explicitly (that is, the switch "succeeds"), control merely goes to the end of that block, and thence on to the next iteration of the loop. You must use last (or some more violent control exception such as return) to break out of the entire loop early. Of course, an explicit next might be clearer than a break if you really want to go directly to the next iteration. On the other hand, break can take an optional argument giving the value for that iteration of the loop. As with the .leave method, there is also a .break method to break from a labelled block functioning as a switch:


Exception handlers ^

Unlike many other languages, Perl�6 specifies exception handlers by placing a CATCH block within that block that is having its exceptions handled.

The Perl�6 equivalent to Perl�5's eval {...} is try {...}. (Perl�6's eval function only evaluates strings, not blocks.) A try block by default has a CATCH block that handles all exceptions by ignoring them. If you define a CATCH block within the try, it replaces the default CATCH. It also makes the try keyword redundant, because any block can function as a try block if you put a CATCH block within it.



Control Exceptions ^



A return always exits from the lexically surrounding sub or method definition (that is, from a function officially declared with the sub, method, or submethod keywords). Pointy blocks and bare closures are transparent to return. If you pass a closure object outside of its official "sub" scope, it is illegal to return from it. You may only leave the displaced closure block itself by falling off the end of it or by explicitly calling leave.


Hence, the leave function:


is really just short for:


To return from your immediate caller, you can say:


Further contexts up the caller stack may be located by use of the context function:

    context({ .labels.any eq 'LINE' }).leave(1,2,3);






If there is no such lexically scoped outer loop in the current subroutine, then a fallback search is made outward through the dynamic scopes in the same way Perl�5 does. (The difference between Perl�5 and Perl�6 in this respect arises only because Perl�5 didn't have user-defined control structures, hence the sub's lexical scope was always the innermost dynamic scope, so the preference to the lexical scope in the current sub was implicit. For Perl�6 we have to make this preference explicit.) So this fallback is more like the context form we saw earlier.




The goto statement ^


Exceptions ^

As in Perl�5, many built-in functions simply return undef when you ask for a value out of range, or the function fails somehow. Perl�6 has Failure objects, any of which refers to an unthrown Exception object in $! and knows whether it has been handled or not.

If you test a Failure for .defined or .true, it causes $! to mark the exception as handled; the exception acts as a relatively harmless undefined value thereafter. Any other use of the Failure object to extract a normal value will throw its associated exception immediately. (The Failure may, however, be stored in any container whose type allows the Failure role to be mixed in.) The .handled method returns false on failures that have not been handled. It returns true for handled exceptions and for all non-Failure objects. (That is, it is an Object method, not a Failure method. Only Failure objects need to store the actual status however; other types just return True.)

Because the contextual variable $! contains all exceptions collected in the current lexical scope, saying die $! will throw all exceptions, whether they were handled or not. A bare die/fail takes $! as the default argument.

At scope exit, $! discards all handled exceptions from itself, then performs a garbage-collection check for all remaining (unhandled) exceptions. If all of them are still alive (e.g. by becoming part of the return value), then they are appended to CALLER::<$!>. Otherwise, it calls die to throw those exceptions as a single new exception, which may then be caught with a CATCH block in the current (or caller's) scope.


    use fatal;


Closure traits ^

A CATCH block is just a trait of the closure containing it. Other blocks can be installed as traits as well. These other blocks are called at various times, and some of them respond to various control exceptions and exit values:



      LEAVE {...}       at every block exit time 



      CATCH {...}       catch exceptions, before LEAVE
    CONTROL {...}       catch control exceptions, before LEAVE


    my $compiletime = BEGIN { localtime };
    our $temphandle = START { maketemp() };

Code that is generated at run time can still fire off CHECK and INIT blocks, though of course those blocks can't do things that would require travel back in time.


    my $r will start { .set_random_seed() };



    our $i = 0;






Note: Apocalypse 4 confused the notions of PRE/POST with ENTER/LEAVE. These are now separate notions. ENTER and LEAVE are used only for their side effects. PRE and POST must return boolean values that are evaluated according to the usual Design by Contract (DBC) rules. (Plus, if you use ENTER/LEAVE in a class block, they only execute when the class block is executed, but PRE/POST in a class block are evaluated around every method in the class.) KEEP and UNDO are just variants of LEAVE, and for execution order are treated as part of the queue of LEAVE blocks.

FIRST, NEXT, and LAST are meaningful only within the lexical scope of a loop, and may occur only at the top level of such a loop block. A NEXT executes only if the end of the loop block is reached normally, or an explicit next is executed. In distinction to LEAVE blocks, a NEXT block is not executed if the loop block is exited via any exception other than the control exception thrown by next. In particular, a last bypasses evaluation of NEXT blocks.


LEAVE blocks are evaluated after CATCH and CONTROL blocks, including the LEAVE variants, KEEP and UNDO. POST blocks are evaluated after everything else, to guarantee that even LEAVE blocks can't violate DBC. Likewise PRE blocks fire off before any ENTER or FIRST (though not before BEGIN, CHECK, or INIT, since those are done at compile or process initialization time).

Statement parsing ^

In this statement:

    given EXPR {
        when EXPR { ... }
        when EXPR { ... }

parentheses aren't necessary around EXPR because the whitespace between EXPR and the block forces the block to be considered a block rather than a subscript. This works for all control structures, not just the new ones in Perl�6. A top-level bare block is always considered a statement block if there's space before it:

    if $foo { ... }
    elsif $bar { ... }
    else { ... }
    while $more { ... }
    for 1..10 { ... }

You can still parenthesize the expression argument for old times' sake, as long as there's a space between the closing paren and the opening brace. You must parenthesize the expression if there is a bare block or pointy block that would be misinterpreted as the statement's block. This is regardless of whether a term or operator is expected where the block occurs. (A block inside brackets, or used as a postcircumfix is fine, though.) Any block with whitespace in front of it will be taken as terminating the conditional, even if the conditional expression could take another argument. Therefore

    if rand { say "exists" } { extra() }
    if rand -> $x { say "exists" } { extra() }

is always parsed as

    if (rand) { say "exists" }; { extra() }
    if (rand) -> $x { say "exists" }; { extra() }

rather than

    if (rand { say "exists" }) { extra() }
    if (rand (-> $x { say "exists" })) { extra() }

Apart from that, it is illegal to use a bare closure where an operator is expected. (Remove the whitespace if you wish it to be a postcircumfix.)

Anywhere a term is expected, a block is taken to be a closure definition (an anonymous subroutine). If the closure is empty, or appears to contain nothing but a comma-separated list starting with a pair or a hash (counting a single pair or hash as a list of one element), the closure will be immediately executed as a hash composer.

    $hash = { };
    $hash = { %stuff };
    $hash = { "a" => 1 };

    $code = { ; };
    $code = { @stuff };
    $code = { "a", 1 };

If you wish to be less ambiguous, the hash list operator will explicitly evaluate a list and compose a hash of the returned value, while sub introduces an anonymous subroutine:

    $hash = hash("a", 1);


    if $term{$x}        # subscript because postfix expected
    if $term\ .{$x}     # valid subscript with "unspace"

Similar rules apply to array subscripts:

    if $term[$x]        # subscript because postfix expected
    if $term\ .[$x]     # valid subscript with "unspace"

And to the parentheses delimiting function arguments:

    if $term.($x)       # valid function call with dot








Then you can say things like:

    $recompile_by = BEGIN { time } + $expiration_time;


    die if $foo;



    if(...) {...}
    while(...) {...}
    for(...) {...}

Definition of Success ^



In the absence of error exception propagation, a successful exit is one that returns a defined value in scalar context, or any number of values in list context as long as the length is defined. (A length of +Inf is considered a defined length. A length of 0 is also a defined length, which means it's a "successful" return even though the list would evaluate to false in a boolean context.) A list can have a defined length even if it contains undefined scalar values. A list is of undefined length only if it contains an undefined generator, which, happily, is what is returned by the fail function when used in list context. So any Perl�6 function can say

    fail "message";

and not care about whether the function is being called in scalar or list context. To return an explicit scalar undef, you can always say

    return undef;


When is a closure not a closure ^

Everything is conceptually a closure in Perl�6, but the optimizer is free to turn unreferenced closures into mere blocks of code. It is also free to turn referenced closures into mere anonymous subroutines if the block does not refer to any external lexicals that should themselves be cloned. In particular, named subroutines in any scope do not consider themselves closures unless you take a reference to them. So

    sub foo {
        my $x = 1;
        my sub bar { print $x }         # not cloned yet
        my &baz = { bar(); print $x };  # cloned immediately
        my $code = &bar;                # now bar is cloned
        return &baz;




syntax highlighting: