Understanding code blocks and variable scoping
In the previous chapter, we discussed variables, which are named entities that you use in a program. As in many programming languages, in Perl 6, the names are visible inside their scope and not outside of it.
Take, for instance, a simple program, where the $name
variable is only used once, as follows:
my $name = 'Mark'; say "Hello, $name!";
The variable can be reused after it is used in printing the greeting:
my $name = 'Mark'; say "Hello, $name!"; $name = 'Carl'; say "Hello, $name!";
This works because both the printing statements are located in the same scope and the $name
variable is visible there.
A block in Perl 6 is a piece of code that is located inside a pair of curly braces. A block creates its own scope. Thus, a variable declared in a block is only visible inside it.
The following program will not compile:
{ my $name = 'Mark'; say "Hello, $name!"; } $name = 'Carl'; # Error here say "Hello, $name!";
The following error message informs...