3 Perl6::Perl5::Differences -- Differences between Perl 5 and Perl 6
7 This document is intended to be used by Perl 5 programmers who are new to Perl
8 6 and just want a quick overview of the main differences. More detail on
9 everything can be found in the language reference, which have been linked to
12 This list is currently known to be incomplete.
18 =head1 Bits and Pieces
22 Where you used to say:
24 my @fruits = ("apple", "pear", "banana");
25 print $fruit[0], "\n";
29 my @fruits = "apple", "pear", "banana";
32 Or even use the C<< <> >> operator, which replaces C<qw()>:
34 my @fruits = <apple pear banana>;
36 Note that the sigil for fetching a single element has changed from C<$>
37 to C<@>; perhaps a better way to think of it is that the sigil of a
38 variable is now a part of its name, so it never changes in subscripting.
40 The same applies to hashes:
42 say "There are %days{'February'} days in February";
44 Again, there is a shorter form:
46 say "There are %days<February> days in February";
48 For details, see L<S02/"Names and Variables">.
50 =head2 Global variables have a twigil
52 Yes, a twigil. It's the second character in the variable name. For globals,
58 For details, see L<S02/"Names and Variables">.
60 =head2 New ways of referring to array and hash elements
62 Number of elements in an array:
64 Was: $#array+1 or scalar(@array)
67 Index of last element in an array:
72 Therefore, last element in an array:
75 Now: @array[@array.end]
76 @array[*-1] # beware of the "whatever"-star
78 For details, see L<S02/"Built-In Data Types">
80 =head2 The double-underscore keywords are gone
90 See L<S02/"double-underscore forms are going away"> for details. The C<?>
91 twigil refers to data that is known at compile time.
95 There are still three main contexts, void, item (formerly scalar) and list.
96 Aditionally there are more specialized contexts, and operators that force that
101 # generic item context
102 my $a = @array; say $a.WHAT; # prints Array
105 say ~@array; # "1 2 3"
111 my $is-nonempty = ?@array;
113 Hyphens C<'> and dashes C<-> are allowed as part of identifiers, as long as
114 they appear between two letters.
122 A comprehensive list of operator changes is documented at L<S03/"Changes to
123 Perl 5 operators"> and L<S03/"New operators">.
127 =head2 C<qw()> changes; new interpolating form
132 Was: ("foo", (split ' ', $bar), "bat")
133 Now: <<foo $bar bat>>
135 Quoting operators now have modifiers that can be used with them (much like
136 regexes and substitutions in Perl 5), and you can even define your own quoting
137 operators. See L<S03> for details.
139 Note that C<()> as a subscript is now a sub call, so instead of C<qw(a b)> you
140 would write C<< qw<a b> >> or C<qw[a b]> (if you don't like plain C<< <a b>
143 =head2 Other important operator changes
145 String concatenation is now done with C<~>.
147 Regex match is done with the smart match operator C<~~>, the perl 5 match
148 operator C<=~> is gone.
150 if "abc" ~~ m/a/ { ... }
152 C<|> and C<&> as infix operators now construct junctions. The binary AND and
153 binary OR operators are split into string and numeric operators, that is C<~&>
154 is binary string AND, C<+&> is binary numeric AND, C<~|> is binary string OR
160 The bitwise operators are now prefixed with a +, ~ or ? depending if the
161 data type is a number, string or boolean.
166 The assignment operators have been changed in a similar vein:
171 Parenthesis don't construct lists, they merely group. Lists are
172 constructed with the comma operator. It has tighter precedence than the list
173 assignment operator, which allows you to write lists on the right hand side
176 my @list = 1, 2, 3; # @list really has three elements
178 The arrow operator C<< -> >> for dereferencing is gone. Since
179 everything is an object, and derferencing parenthesis are just method calls
180 with syntactic sugar, you can directly use the appropriate pair of
181 parentheses for either indexing or method calls:
183 my $aoa = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
186 my $s = sub { say "hi" };
196 =head1 Blocks and Statements
198 See L<S04> for the full specification of blocks and statements in Perl6.
200 =head2 You don't need parens on control structure conditions
202 Was: if ($a < $b) { ... }
203 Now: if $a < $b { ... }
205 Likewise for C<while>, C<for>, etc. If you insist on using parens, make sure
206 there's a space after the C<if>, otherwise it's a sub call.
208 =head2 eval {} is now try {}
210 Using C<eval> on a block is now replaced with C<try>.
220 CATCH { warn "oops: $!" }
223 CATCH provides more flexiblity in handling errors.
224 See L<S04/"Exception_handlers"> for details.
226 =head2 foreach becomes for
228 Was: foreach (@whatever) { ... }
229 Now: for @whatever { ... }
231 Also, the way of assigning to something other than C<$_> has changed:
233 Was: foreach my $x (@whatever) { ... }
234 Now: for @whatever -> $x { ... }
236 This can be extended to take more than one element at a time:
238 Was: while (my($age, $sex, $location) = splice @whatever, 0, 3) { ... }
239 Now: for @whatever -> $age, $sex, $location { ... }
241 (Except the C<for> version does not destroy the array.)
243 See L<S04/"The for statement"> and L<S29/"each"> for details.
245 =head2 for becomes loop
247 Was: for ($i=0; $i<10; $i++) { ... }
248 Now: loop ($i=0; $i<10; $i++) { ... }
250 C<loop> can also be used for infinite loops:
252 Was: while (1) { ... }
259 =head1 Regexes and Rules
261 Here's a simple translation of a Perl5 regular expression to Perl6:
263 Was: $str =~ m/^\d{2,5}\s/i
264 Now: $str ~~ m:P5:i/^\d{2,5}\s/
266 The C<:P5> modifier is there because the standard Perl6 syntax is rather
267 different, and 'P5' notes a Perl5 compatibility syntax. For a substitution:
269 Was: $str =~ s/(a)/$1/e;
270 Now: $str ~~ s:P5/(a)/{$0}/;
272 Notice that C<$1> starts at C<$0> now, and C</e> is gone
273 in favor of the embedded closure notation.
275 For the full specification, see L<S05>. See also:
277 The related Apocalypse, which justifies the changes:
279 http://dev.perl.org/perl6/doc/design/apo/A05.html
281 And the related Exegesis, which explains it more detail:
283 http://dev.perl.org/perl6/doc/design/exe/E05.html
293 Formats will be handled by external libraries.
313 Perl 6 has a "real" object system, with key words for classes, methods and
314 attributes. Public attributes have the C<.> twigil, private ones the C<!>
321 # and with write accessor
324 method do_something {
325 if self.can('bark') {
326 say "Something doggy";
331 =head2 Method invocation changes from -> to .
336 =head2 Dynamic method calls distinguish symbolic refs from hard refs
338 Was: $self->$method()
339 Now: $self.$method() # hard ref
340 Now: $self."$method"() # symbolic ref
348 Since both builtin functions and operators are multi subs and methods,
349 changing their behaviour for particular types is a simple as adding the
350 appropriate multi subs and methods. If you want these to be globally
351 available, you have to but them into the C<GLOBAL> namespace:
353 multi sub GLOBAL::uc(TurkishStr $str) { ... }
355 # "overload" the string concatenation:
356 multi sub infix:<~>(TurkishStr $us, TurkishStr $them) { ... }
358 If you want to offer a type cast to a particular type, just provide a method
359 with the same name as the type you want to cast to.
361 sub needs_bar(Bar $x) { ... }
364 # coercion to type Bar:
368 needs_bar(Foo.new); # coerces to Bar
370 =head2 Offering Hash and List semantics
372 If you want to write a class whose objects can be assigned to a variable with
373 the C<@> sigil, you have to implement the C<Positional> roles. Likewise for
374 the C<%> sigil you need to do the C<Associative> role. The C<&> sigil implies
377 The roles provides the operators C<< postcircumfix:<[ ]> >> (Positional; for
378 array indexing), C<< postcircumfix:<{ }> >>
379 (Associative) and C<< postcircumfix:<()> >> (Callable). The are technically
380 just methods with a fancy syntax.
381 You should override these to provide meaningful semantics.
383 class OrderedHash does Associative {
384 multi method postcircumfix:<{ }>(Int $index) {
385 # code for accessing single hash elements here
387 multi method postcircumfix:<{ }>(*@@slice) {
388 # code for accessing hash slices here
393 my %orderedHash = OrderedHash.new();
394 say %orderedHash{'a'};
396 See L<S13> for all the gory details.
402 =head2 Chaining file test operators has changed
404 Was: if (-r $file && -x _) {...}
405 Now: if $file ~~ :r & :x {...}
407 For details, see L<S03/"Changes to Perl 5 operators"/"The filetest operators now return a result that is both a boolean">
413 # XXX needs some brave rewrite
416 =head1 Builtin Functions
418 A number of builtins have been removed. For details, see:
422 =head2 References are gone (or: everything is a reference)
424 C<Capture> objects fill the ecological niche of references in Perl 6.
425 You can think of them as "fat" references, that is, references that
426 can capture not only the current identity of a single object, but
427 also the relative identities of several related objects. Conversely,
428 you can think of Perl 5 references as a degenerate form of C<Capture>
429 when you want to refer only to a single item.
431 Was: ref $foo eq 'HASH'
434 Was: @new = (ref $old eq 'ARRAY' ) ? @$old : ($old);
437 Was: %h = ( k => \@a );
438 Now: %h = ( k => @a );
440 To pass an argument to modify by reference:
442 Was: sub foo {...}; foo(\$bar)
443 Now: sub foo ($bar is rw); foo($bar)
445 The "obsolete" reference above has the details. Also, look for
446 I<Capture> under L<S02/"Names_and_Variables">, or at the Capture FAQ,
447 L<Perl6::FAQ::Capture>.
451 This is a version of C<print> that auto-appends a newline:
453 Was: print "Hello, world!\n";
454 Now: say "Hello, world!";
456 Since you want to do that so often anyway, it seemed like a handy thing
457 to make part of the language.
461 C<wantarray> is superseded by C<want.list>. Also available are C<want.item>
462 and C<want.count>, the latter gives the number of expected values, if
465 In general you are encouraged to return objects that do the right thing in
466 each possible context instead of asking for your context explicitly.
470 =head2 Hash elements no longer auto-quote
472 Hash elements no longer auto-quote:
475 Now: %days{'February'}
477 Or: %days<<February>>
479 The curly-bracket forms still work, but curly-brackets are more
480 distinctly block-related now, so in fact what you've got there is a
481 block that returns the value "February". The C<<>> and C<<<>>> forms
482 are in fact just quoting mechanisms being used as subscripts (see below).
484 =head2 Built-in functions are now methods
486 Most built-in functions are now methods of built-in classes such
487 as C<String>, C<Array>, etc.
489 Was: my $len = length($string);
490 Now: my $len = $string.chars;
492 Was: print sort(@array);
493 Now: print @array.sort;
496 You can still say C<sort(@array)> if you prefer the non-OO idiom.
500 Kirrily "Skud" Robert, <skud@cpan.org>,