While many of the changes in Perl 6 make it easier for people new to programming or coming from other programming languages to understand the language, none of the changes were made solely on those grounds. If your favorite part of Perl 5 syntax is that it uses an arrow for method dispatch on objects, don't be dismayed that Perl 6 uses a dot instead. The designers carefully considered each syntactic change to ensure that Perl 6 still has the Perlish nature and that the change was an overall improvement. Some Perl programmers delight in the syntactic differences of the language, but some of those differences aren't that important when compared to the big picture of Perl's culture (which includes the language, CPAN, and the community of programmers).
Sigil Invariance
One of the fundamental changes is that whenever you refer to individual elements of an aggregate (an array or hash), rather than changing the sigil to denote the type of thing you get back, the sigil remains the same.
For example, in both Perl 5 and Perl 6 you can create and initialize aggregates:
my @array = (1,3,5,12,37,42);
my %hash = ( alpha => 4, beta => 6 );
How you access the individual elements of those aggregates looks just a little different:
# Perl 6 # Perl 5
my $third = @array[2]; my $third = $array[2];
my $beta = %hash{'beta'}; my $beta = $hash{'beta'};
Long-time Perl 5 programmers might wonder how slices work in Perl 6. The answer is: the same way as in Perl 5.
my @odds = @array[1,3,5]; # array slice
my @bets = %hash{'alpha','beta'}; # hash slice
The only difference is that in Perl 5 the hash slice would have started with a @
sigil.
New Brackets
In these hash examples, it's awkward quoting the indexes into the hash. Perl 5 allows a syntactic shortcut where $hash{word}
works as if you had written $hash{'word'}
. A problem with that is that it can cause confusion when your word
happens to be the name of a subroutine and you really want Perl to execute that subroutine.
In Perl 6, a syntactic shortcut for accessing hash elements takes advantage of a name change of the "quote word" operator:
# Perl 6 # Perl 5
my @array = ; my @array = qw(foo bar baz);
my %hash = ; my %hash = qw(a b c d e f g h);
my $queue = %hash; my $queue = $hash{'q'};
my @vows = %hash; my @vows = @hash{qw(c a g e)};
my $foo = "This is";
my $bar = "the end";
my @blah = << $foo $bar >>; # ('This','is','the','end');
Note that the interpolation happens before the "quote word" aspect of this operator.
my @items = ;
say "Send @items[] to test@foo.com";
# Send names addresses email to test@foo.com
You can also interpolate more things into your double-quoted strings:
say "Send me $person.name()"; # results of a method call
say "2 + 2 = { 2+2 }"; # any bit of perl code
No comments:
Post a Comment