Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What space is significant in Perl 6?

Perl 6 cleans up some odd cases in its predecessor by not allowing spaces in some places but also doing jobs in other places. Where does space matter? It would be nice to have a complete reference and as such I've added a community wiki answer that I'll update with your rep-earning answers. Examples appreciated!

But, also remember that Perl 6 has unspace, so you can use a \ to make whitespace effectively invisible. For example, you aren't supposed to air out the subroutine name and it's argument list, but with unspace you can:

sub-name    ( @arguments );  # not okay
sub-name\   ( @arguments );  # okay
like image 820
brian d foy Avatar asked Aug 02 '17 02:08

brian d foy


1 Answers

Whitespace prevents various paired symbols (e.g. {}, (), <>) from being interpreted as postfix operators

Hash constructs

> my %a = (A=>1, B=>2, C=>3);
{A => 1, B => 2, C => 3}
> %a<A>;
1
> %a <A>;
===SORRY!=== Error while compiling:
Missing required term after infix
------> %a <A>⏏;
    expecting any of:
        prefix
        term
> %a\ <A>;
1

Likewise, interpolating is broken by spaces and I don't know of a way to use unspace in an interpolating environment. But you can introduce space after an opening { when using {} to interpolate the result of code:

> put "%a<A>";
1
> put "%a <A>";
%a <A>
> put "%a\ <A>";
%a <A>
> put "%a {'A'}"
%a A
> put "%a{<A>}"
1
> put "%a{ <A> }"
1

loop blocks

This loop works in Perl 5, but not in Perl 6:

for (1,2,3){
    print "counting $_!\n";
}
===SORRY!=== Error while compiling testing.p6
Missing block (whitespace needed before curlies taken as a hash subscript?)
at testing.p6:4
------> <BOL>⏏<EOL>
    expecting any of:
        block or pointy block

But a space after the closing parentheses corrects this:

for (1,2,3) {
    print "counting $_!\n";
}
counting 1!
counting 2!
counting 3!

This used to catch me all the time, until I learned to that the parentheses are usually not needed for the conditional of control flow constructs (e.g. for, while, and if constructs).

To avoid this, simply leave out the parentheses:

for 1,2,3 {
    print "counting $_!\n";
}

But you still have to leave space before the brace:

for 1,2,3{
    print "counting $_!\n";
}
===SORRY!=== Error while compiling testing.p6
Missing block (whitespace needed before curlies taken as a hash subscript?)
at testing.p6:4
------> <BOL>⏏<EOL>
    expecting any of:
        block or pointy block
like image 77
Christopher Bottoms Avatar answered Sep 30 '22 18:09

Christopher Bottoms