Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
This week, we're updating our course layouts and descriptions. Presentation and materials always gently change over time, but just occasionally there's a need to make a step change to clear out some of the old and roll in the new. That's now happening - but over a long and complex site it's not instant and you'll see sections of the site changing up to and including 19th September.

See also [here] for status update
 
Overview of what we're expecting in Perl 6

The rewrite of Perl 5 into the new Perl 6 language is underway; now that Perl is a teenager, it's showing signs of age that would make it hard to develop it forward while maintaining compatibility with code that was written in its early childhood, so the very brave decision has been taken that this will be a new language. There will be good tools to help you convert your source - automatically in most cases, Perl 6 will have "Perl 5 modes" in one or two areas, and the underlying philosophies of Perl remain. The P of Perl will still stand for practical. The language will still be eclectic, and will still assume you know what you're doing as you code. If you don't know what some structure does, it still probably does the sensible thing - indeed a term for this "DWIM" - "Do what I mean" has been coined.

As I write this document - late summer, 2002, The Perl 6 specification is pretty close to being "there". There has been a whole series of conversations and discussions via the RFC ("Request for comment") mechanism, and the Perl community has made good input. Now, Larry Wall and team are working on the detail - the minutiae - and in certain areas the coding of the language itself, though there are still aspects to be decided. In some areas (such as "Parrot" that we'll come back to), there's already some early experimental code around.

[Updated - Autumn 2004. You'll find further comment on the Perl 6 timetable and progress elsewhere on this site. The language description in this document remains almost entirely correct - things to note:
 * "Ponie" - Perl on New Internal Engine - which will use Parrot for Perl 5
 * Estimated early access testing releases towards the end of 2005]

This doesn't mean that you should wait for Perl 6 before you do any more coding (you would have a long holiday!), nor that Perl 5 development has stopped. Currently, the 5.8 release is available for production use, a 5.9 development thread is starting which will include a few of the aspects also slated for Perl 6, and there's every intention that there will be a 5.10 production release which will be a final, stable Perl 5. Perl 5.10 will probably survive for years, just like Perl 4.036 did (or should I say "does ;-) ). Rather, listen to this presentation (or read the notes), and marvel at the shear genius of what Larry's come up with .... then go forward with Perl confident that it's not about to be usurped by some language such as Java or C#.

OBJECTS

In Perl 6, everything is an object, and has *PROPERTIES*. That doesn't just mean that what you create is an object; it means that the Perl built in types are objects too, and you use methods to set or discover things about them, or get them to do things. You want to get the number of elements in a list?
  @aaa.getprop(length)
should work for you, but then being Perl that'll be shortened down to
  @aaa.length
if you like or even
  +@aaa
(OK - ask about that last one later).

There's a proper class keyword to define classes (you, you can still define Perl 5 packages if you wish), and you still bless the main structure using the bless function; you will be forced to use the two parameter form of bless, by the way. You can also define extra properties that will be maintained for each object separate from the blessed structure, using the attr (for attribute) keyword.

Inheritance will be defined using the "is" keyword on the class declaration, rather than the kludged @ISA; thus
  class dog is animal

Since everything's an object, with attributes, you can read and write some surprising settings on something as "simple" as a scalar. Let's say that you want to set a variable to contain a numeric value, and have that value be true.
  $demo =16;
Yes, that's true in Perl 5 and also in Perl 6
  $demo = 0;
Oops - that has a value of zero, but if you test it in Perl 5 it will give you a false value. That might not be what you want - you might want it to be true even though it's zero. So in Perl 6 ...
  $demo = 0 but true;
and the attribute is set. If you wonder about things like this, think how useful it will be to return a value from a subroutine, and also to return a flag to say "yes, this is a valid number" even if the number is 0.

OPERATORS

STRING HANDLERS

$(....) will evaluate an expression in a scalar context, and @(....) will evaluate an expression in a list context. So
  print ("Please enter number ",$n+1,": ");
becomes
  print ("Please enter number $($n+1): ");

The old concatenation operator, ".", has been taken away to become the "method" operator; really the only sensible option for the method operator, as it's become such a standard in most other languages. A new operator "_" replaces the "." for string concatenation; since _ is valid in a variable name, it'll have to be used with white space just as has always been the case with operators such as "x".

Here documents always had to be coded up against the left margin; no longer so, as you can inset the final delimiter by a certain number of spaces, and then each line will be considered inset that same amount. Other changes allow you to place the ; on the terminator line, and force you to quote the initial terminator. Thus

 while ($j = pop (@stuff)) {
  print <<DONE
 There is a record called $j
 which is printed here
 DONE
        ;
  }
 print "And that's your lot\n";

becomes

 while ($j = pop (@stuff)) {
  print << "DONE"
   There is a record called $j
   which is printed here
   DONE ;
  }
 print "And that's your lot\n";

COMPARISON OPERATORS

Ever wanted to write
  if (1 < $x < 10) ....
Well - it will work in Perl 6. But what will it do? It will do what I mean - DWIM! In this example, it'll check that the contents of $x has a value (in a numeric context) that's between 1 and 10. You could also write
  if ($a != $b != $c) ...
but you'll need to be careful - that'll check that neither $a nor $c is equal to $b - $a and $c COULD have the same value and the whole expression will still be true. Oh - by the way, $a and $b are no longer special variables ;-)

Ever got yourself mixed up between ==, eq and =~? Ever found yourself comparing numbers when you should be comparing strings? Enter the smart match operator:
 if ($a ~~ 20) That's numeric
 if ($a ~~ "Twenty") That's an exact string match
 if ($a ~~ /dog/) That's "contains"
The ~~ operator does "intelligent matching", where what it matches depends on the type (and perhaps the contents) of the operands passed to it ....
 if (@a ~~ 29) Is there a value "29" in the list @a?
 if (@a ~~ @b) Are lists @a and @b identical?
 if (%a ~~ "dog") Is there an element keyed "dog" in %a?
And so on to a total of 35 different operations

[October 2004 - the original Perl 6 spec was for the =~ operator to be widened to do intelligent matching, but this plan has been replaced by the new ~~ operator]

Perl 5's "or" operator (and the || operator too) work a treat for giving answers "a" or "b" or "c" ... except when one of the input values is false. You may well have written
  $abc ||= 16;
to set $abc to 16 if it didn't already have a value. You may well have been caught by the trap that if $abc already existed, but with a false value, that value would be overwritten with the number 16. Enter the err or // operator:
  $abc //= 16;
to set $abc to 16 if it doesn't have a value yet.

err and ~~ may look exotic, but we rather suspect that they'll be the operators of choice in Perl 6 coding once it's established, and operators such as ==, eq and or will gently fade into the backwaters.

VECTORISED OPERATORS

You want to add one to every element of a list? Write a loop? Use the map function? Sure - you can do either - OR you can use a vectorised operator. If you add a ^ in front of an operator, it will apply the operation to every element of the list, and if either of the operands is shot of values - as it would be in the case of a scalar - that operand is stretched.

Thus:
 @result = @x ^- @y;
gives you a result list where every element of y is subtracted from every element of x. and:
 @result = (@x ^+ @y) ^/ 2;
computes a list of averages and:
 @result ^+= 1;
adds one to each element of the result list.

DATA TYPES

File handles aren't a special limited type of variable any more - they're objects that can be held in scalars. You want to open a file?
  $fh = open("abc.txt");
"Typeglobs" are gone too ... but see "bindings" later ;-)

Internally, Perl 6 will still use long and double integers, but it will no longer get into trouble when you burst the limits of these data types; internally, it will switch to using arbitrary precision / accuracy numbers of type BIGINT or BIGNUM. Significance for the programmer? usually none; the change is automatic and invisible. For sure, code will slow down when big numbers comes into play, but at least you'll get the correct answers.

Hashes are implemented as tables of pairs. Don't worry too much about that one at the moment, but note that you can write
 @stuff = %hash.kv;
to get a list of key, value, key, value, .... where in the past you would just have written
 @stuff = %hash;

BINDINGS

The := operator allows you to bind an (extra) name to a variable.

In Perl (any version!), a variable has comprised two parts - the memory that's used to hold the value(s) associated with the variable, and the name itself, held in a symbol table. The memory management system keeps note of how many references there are in the symbol table, directly or indirectly, to each variable's data, so that memory can be "garbage collected" from time to time.

In addition to the $ and \ operators, which will still be available, Perl 6 introduces a new operator :=. It's known as the binding operator, and it means "is also a name for". Let's see an example:
  $x = 16;
  $y := $x;
  $y++;
  print $y;
will print out the value 17.

Great theory. Practical uses? Many many many! Try this for starters:
  (@a, @b) := (@b, @a);
Swap over the names of lists @a and @b - very efficient, no need to start copying great swathes of data around in memory.

SUBROUTINE BINDINGS

Yes, you can still use @_ if you want to write job protection code ;-) ... but much better use named parameters. Remember:
  sub somename {
   my ($first, $second) = @_;
   $third = $first + $second;
   etc;
Well - do you prefer this:
  sub somename ($first, $second) {
   $third = $first + $second;
   etc;
Much better. But you can go further:
  sub somename {
   $third = $^first + $^second;
   etc;

Perhaps we had best explain. If you start a variable name $^, you're referring to a calling parameter for the block your in (oh - all blocks are subroutines now), and Perl will Asciibetically sort all such variable names so that you don't need to declare them at all - Perl will work out the order.

If you're porting your own sort subroutine from Perl 5, just replace $a with $^a and $b with $^b; Perl 6 now uses parameters to collect the two elements it's to compare, and no longer has that wart of the special variables $a and $b. This also means that you can run a sort which involves another sort internally; old global conflicts are gone!

You can now call subroutines with multiple lists, such as:
  myjob(@list1,@list2);
and they won't get slurped together into a single list in the subroutine; if you do need to have a "slurpy list" type parameter, an extra "*" preceding the variable name will give you that:
  sub example ($one,$two,*@three) {
declares a subroutine with two scalar parameters, and then all the rest of the parameters will get slurped into the @three list. By contrast:
  sub example ($one,$two,@three) {
declares a subroutine that takes three parameters, and calling it with more would be an error. Yes, this does open the way for Perl 6 to define a number of subroutines all with the same name, and have different ones called depending on the calling sequence. Notice a similarity to Java's "overloading"? Syntax / rules for this capability are still being worked on.

You may have come across examples of methods being called in Perl 5 where a hash is passed in, the keys being used to instruct which parameters are set. Perl 6 has a direct => operator that can be used in the call to pass in a pair, which is a new data type; a hash becomes a table of pairs.

"All blocks are subroutines" - remember? You can declare
 $var = { code ...........}
and then
 if ($j !~ 10) $var;

Finally, you can bind a subroutine with an assumption. Let's say that you have a subroutine that returns one number divided by another:
  sub div {$^x / $^y}
and you want to define another subroutine that returns you a reciprocal, without the need to rewrite all the code (!). Well:
  $rec := &$div.prebind(x => 1);
 or
  $rec := &$div assuming x => 1;


CONDITIONALS AND LOOPS

TOPICALISATION

"What?" you ask, with a shudder. OK - we're talking $_. You're used to leaving out a variable name in Perl 5, and having it work with the contents of $_; we make a bit of a game of this on our beginner's courses for Perl. Like everything else in Perl 6, and excellent concept has been breathtakingly extended.

SWITCH STATEMENTS

No, you still don't have a Switch keyword in Perl 6. Rather, you have a given. Let's try an example:

 given $val {
  when 17 { code to perform}
  when 19 { code to perform}
  when "n/a" { code to perform}
  when m:i/end/ {code to perform}
  default {code to perform}
  }

The given statement topicalises $val ( OK - write $_ = $val is you like!), and then each when statement does a smart match. If $val works out to the number 17, the first block is performed; if it works out to 19, then the second block is selected instead. If it contains the text "n/a", then the third block is performed, and if it matches the regular expression /end/, ignoring case, then the penultimate block is performed. No match at all, and the final block after the world "default" is performed.

You'll note that there's no need to bracket the condition after the "when", and that's now a common feature of all conditional and loop statements. For sure, you can write
  when ($ab) {print "It matches \$ab\n";}
but you can also write
  when $ab {print "It matches \$ab\n";}
There does have to be a space before the { character; that's how Perl 6 can tell a member of a hash apart from a code block. Seems a small price to pay - after all, whoever wants to leave spaces within variable names?

At then end of a successfully completed when block, Perl 6 will jump out of the given construct; no need to specify a break (you can if you wish, though), or a breaksw or anything like that. Larry has provided you with a continue statement that lets you continue on to the next "when" if you really want to.

Have a look at this ....
   
 given $val {
  when < 10 { print "Much "; continue}
  when < 21 { print "Reduced Rate"}
  $fullfare++;
  when > 65 { print "Senior"}
  print "Regular"
  }

FOR AND LOOP

Perl 6's loop command replaces the traditional for loop of Perl 5, and C and many other languages. At its simplest:
 $value = 1;
 loop {
  $value *= 2;
  print "$value \n";
  $count ++;
  $count < 10 or break;
  }
or a little for complex:
 $value = 1;
 loop ($count=0; $count<10; $count++) {
  $value *= 2;
  print "$value \n";
  }

The for loop is now an iterator that lets you step through something (at its simplest, a list):
 for @data { print }

Topicalises each member of @data in turn, and passes each to the subroutine that's declared as the thing to be performed. If you don't say anything about the parameters to a subroutine, the first parameter is taken to be $_, and print defaults to printing out $_ as it always has done!

If I want to name my variables in a for loop, I can do so:
 for @data -> $scvar { print $scvar}
and:
 for @data { print $^scvar}
will both work, and I can also write a more complex structure:
 for @x,@y -> $m,$n {
  print "$m $n\n"}
to iterate through @x and @y at the same time - this latter example will print out element 0 of both lists, then element 1 of both lists, and so on. You want to see another?:
 for @x;@y -> $r {
  print "$r\n"}
will print out alternately elements of @x and @y. You may spot some similarity to iterating through a list in Tcl if you're familiar with that language.

Finally
 for %demohash { print .key}
will let you print out all the keys of a hash. If you're wondering, the for statement topicalises each element of the hashtable in turn. Then any method that isn't told what to run on (in this case the key method, told to run, but not told what to run on), runs on the current topic.

EXCEPTION HANDLING

Perl 6 will return any errors as objects in $! (that's much simpler than the use of $! $@ $^E and - oh I forget the other ones - in Perl %). You can then run methods on the object to learn more about the error. Some of these methods use the "." notation, and others use a "Sigil" character in front of the variable to force a context. Thus
 +$! $! as a number
 _$! $! as a text string
 ^$! $! as a boolean.
These notations are available elsewhere in Perl 6 too; the whole language is much tidier with far fewer special cases.

TRY BLOCKS.

When you run a piece of code, it may work or it may fail. If it fails, you want to trap the failure - and you can do this in Perl 6 using a catch block.

 @demo = (10,20,30,0,50);
 try {
  CATCH { print "Oops - division failure\n"]
  for @demo {print 1/$^each}
 }

The loop attempts to print the reciprocal of each of the members of a list, but if it fails the error is caught and an error message is printed instead. If the whole try block runs successfully (if, say, our demo list didn't include a zero element), then the catch block would never be run.

You'll notice that the catch block is inside the try block; using that structure, the CATCH block has access to locally scoped variables within the try - a much better solution that you'll find in Java, for example. The word CATCH is capitalised; by way of explanation, any block that is capitalised is set aside for possible later user - it's a trap, an error handler, an initiator or whatever. You may have come across BEGIN END and DESTROY in Perl 5, and there were also CHECK and INIT blocks. In Perl 6, not exclusively associated with Try, you also have
 PRE Condition that must be true on block entry
 POST Condition that must be true on block exit
  (These two very useful during code development)
 KEEP To be performed on block exit if it succeeded
 UNDO To be performed on block exit if it fails
 FIRST First time through a block only
 LAST Last time through a block only

Blocks such as CATCH can take a condition, so that they'll only catch certain things, and you can supply multiple CATCH blocks within a single try. Where you place the blocks within the try is up to you.

RULES AND GRAMMARS

If you're a newcomer to Perl, you'll find regular expressions powerful but obtuse and hard to learn; if you're an old hand, you'll swear by regular expressions but you'll want so much more.

Perl 6 doesn't describe things as "regular expressions" - it described them as "rules". And a series of rules can be combined to make up a grammar. Perl 6 itself can be defined as a grammar, and you can amend and alter that grammar if you want, thus changing Perl with minimal coding. Don't try that yet ;-)

In rules (previously known as regular expressions), some things remain unchanged. Literal letters and digits still match exactly, \ in front of a special character will cause that to match exactly, and you'll have grouping with (), alternation with |, and counts such as * + and ? (greedy) and *? +? and ?? (sparse) just as you're familiar with.

MODIFIERS

Rule modifiers are now written at the beginning of the rule, and not at the end. So that
 if ($x ~~ /end/i) {....
becomes
 if $x ~~ m:i/end/ {....

The old /x modifier has gone (by default, and white space in a regular expression is now a comment) and so have the /s and /m modifiers; they should really have been defined within regular expressions in the first place, and not as modifiers.

The /e for execute modifier on s has gone. Just look at this elegant solution:
 $j ~~ s/(\w+)/ucfirst(\1)/eg;
becomes
 $j ~~ s:g/(\w+)/$(ucfirst($1))/;
using the new $(...) notation that we've already seen elsewhere in Perl 6.

Other modifiers:
 :c continue (carry on, rather like g in a scalar context)
 :o once only
 :w any white space in the expression is \s* or \s+, this latter
  if the white space appears between two words
 :p5 Please use Perl 5 Regular expressions!
and on s, you might want to use:
 :4x do 4 substitutes
 :3rd substitute the third match
 :e3rd substitute every third match

ELEMENTS WITH A RULE

- Assertations

^ and $ match the beginning and end of the string (just as they always did unless you had used the /m modifier), and you're also provided with ^^ and $$ which will also match at the beginning and end of embedded lines. \a \z and friends have gone.

- Grouping.

( ...) is still a grouping. Did you like (?: .... ) as "group but don't capture" in the past? Thought you didn't! You can now use [.....] for group but don't capture. You can also use { ...... } to embed some code within a regular expression. Thus:
 when /(\d+){$1 < 256 or fail}/
if you want to check for a numeric value (series of digits) which works out whether or not a number less than 256 is present.

- Variables within rules

A scalar variable within a rule is matched literally - thus
 $var ="Hello?";
 if (/$var/) {
will match $_ for the literal text H-e-l-l-o-? in Perl 6, whereas it would have matched H-e-l-l followed by 0 or 1 letter o's in Perl 5. If you include a list in a Perl 6 regular expression:
 if (/@lis/) {
you'll look for a match to any member of the list (a very neat way of searching to see if something's present in a list), and if you include a hash, you'll check for the existence of an element with the given key.

These extra facilities for variables will save you a lot of
 \Q$var\E
type stuff, but in any case the \E has gone in favour of non-capture bracket groups:
 \Q[Hello?]
for example.

- Metasyntax

If you're wondering what has happened to the old character groups that used square brackets, welcome Metasyntax, written between < and > characters. Metasyntax includes a wide range of possibilities, including
 <sign> a sign character
 <'literal'> a literal piece of text
 <$var> interpolated variable (if you REALLY want to!)
 <ws> white space - just like \s+
 <sp> a space character
 <(....)> a code assertion


CAPTURING

When you want to capture groups in a rule, you can do so using syntax such as
  (\d+){let $num := $1}
which you can simplify down to
  $num := (\d+)

Very neat - naming and capture all within the rule (no assignment of a list necessary, and the ability to capture nested brackets if you wish.

CONCLUDING RULES AND GRAMMARS

There's so much that's new in Perl 6's rules and grammars, (we haven't described <commit>, <null>, <prior>, <before ...>, :, ::, :::) that for most users the best advice is "it's good, but wait until you have a rule engine in your hands to experiment with before you try and learn the whole thing". Uniquely amongst all the features that we've described in this document, the features and changes are so far reaching that it's probably best to learn rules as a new topic rather than to try and convert your existing regular expression knowledge.

UNDER THE BONNET

With Perl 5, you wrote your source code into a file, and said "run that file". You'll do the same thing, if you want, with Perl 6.

Internally, Perl 5 converted your script into a series of operations and opcodes via a compiler, and it then used the resulting Btree to run your program; although it wasn't initially called a "virtual machine", that's really what it was.

Perl 6 will use the new "Parrot" virtual machine, which is being designed and written in parallel with the language specification and development; there are already parrot assemblers and test code available - that's been the case for quite a while now - and Parrot will support other languages other than Perl.

As well as having a shiny new car in Perl 6, you'll have a fresh, clean-burn engine that can run on other fuels too.

CONCLUSION

Perl 6 is an exciting rewrite of the Perl language, adding facilities to take it forward for the next generation. It's well though out, clever, powerful and follows the philosophies of earlier Perls that we've grown to know and love. It bravely adds facilities, and it bravely breaks compatibility where that was seriously necessary for the future.

Perl 6 is exceptionally feature rich, and it's not going to be the sort of language you can learn and become fluent in overnight; it's going to take time to learn, and you're going to need to to use it with care. As Damian Conway, one of the key players in writing Perl 6 said at a recent lecture in London: "We're giving you all this power in Perl - now go out there and use it carefully" ....

[Disclaimer. Although every attempt has been made to correctly interpret the information that we have on hand on Perl 6, we cannot take any liabilities for any errors or omissions. You should also be aware that Perl 6 is currently under development, and there is a chance that some elements described may change prior to its production release


See also Perl 6 look-ahead - training module

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Perl 6 Look Ahead
  [3077] Perl 6 - significantly nearer, and Rakudo looks very good - (2010-12-02)
  [2967] Multiway branches in Perl - the given and when syntax - (2010-09-22)
  [2817] Setting a safety net or fallback value in Perl - (2010-06-19)
  [2816] Intelligent Matching in Perl - (2010-06-18)
  [2815] switch and case, or given and when in Perl - (2010-06-17)
  [2559] Moving the product forward - ours, and MySQL, Perl, PHP and Python too - (2010-01-01)
  [1721] Perl 6 - When will we have a production release? - (2008-07-26)
  [1417] What software version do we teach? - (2007-10-31)
  [1215] An update on Perl - where is it going? - (2007-06-03)
  [995] Ruby's case - no break - (2006-12-17)
  [582] DWIM and AWWO - (2006-01-30)
  [550] 2006 - Making business a pleasure - (2006-01-01)
  [113] A Parallel for Perl 6 - (2004-11-09)
  [89] When will Perl 6 be available - (2004-10-15)

resource index - Perl
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/perl-ove ... erl-6.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard