----
presentation_topic: Apocalypse Now
presentation_title: Perl 6 is Here Today
presentation_place: http://autrijus.org/apoc/start.html
presentation_date: June 9th, 2005
----
{image: http://perlcabal.org/~autrijus/today.jpg}

Apocalypse Now

Autrijus Tang

/pugscode.org/

----
{image: http://perlcabal.org/~autrijus/images/earendils_ship_port.jpg}

    A ship then new they built for him
    of mithril and of elven glass.

                          -- Perl 5.0.0, perl.c

----
{image: http://perlcabal.org/~autrijus/images/ship.jpg}

    Sie bauten ihm ein neues Schiff
    Aus Mithril und aus Elbenglas
    Mit stolzem Bug, doch ruderlos,
    Mit Silbermast, doch ohne Tuch,
    Und Elbereth kam selbst herab:
    Sie schuf dem Schiff den Silmaril
    Zum Banner, ein lebendiges Licht,
    Ein heller Schein, der nie verblaßt.

                          -- Pugs 6.2.7, Main.hs
----

    use v6;

    for $*Larry {
        our Ship $pugs .= new(:of<mithril elven-glass>);
        given $pugs {
            $.prow does Shine;
            Silver $.mast but none(Oar::Shaven, Sail);
            Light  $.lantern := $*Silmaril;
            Bright $.banner  := Flame.bless:{};
            when $*Elbereth.gleam {
                .sail(...);
            }
        }
    }
                          -- examples/poetry/pugs_main.p6

----
== Perl 6 is Here Today!

{image: http://perlcabal.org/~autrijus/images/apoc.jpg}

* I'm glad Jens covered the /Perl 6/ part...
+* ...that means I get to focus on the /is Here Today/ part.

----
== But First...

{image: http://perlcabal.org/~autrijus/images/camel.jpg}

* Perl 5 is Here Today!
+* The transition from Perl 4 succeeded!
+** ...although it took us four years
** 5.000a1 (1993) ~ 5.004 (1997)
+** ...or six years for Win32 people
** 5.005_03 (1999)
+** ...or nine years for jcode.pl people
** 5.8.0 (2002)
+* It was really an amazing new language!

----
== Perl 5: References

    $code->($arg);
    $hash->{3};
    $obj->method($arg);

+    { hash => 1 }
    [ 'array' ]
+    \eval{'scalar'}

----
== Perl 5: Closures

{image: http://perlcabal.org/~autrijus/images/closure.gif}

    my $var;

    $code = sub { ... };

    for my $i (1..10) { ... };

----
== Perl 5: Modules

{image: http://perlcabal.org/~autrijus/images/packages.jpg}

    use strict;
    no warnings;

    $Package::name = 1;

    bless($reference => 'Package');
    tie($container => 'Package');

----
== But even more importantly...

{image: http://perlcabal.org/~autrijus/images/cpan.jpg}

* CPAN is Here Today (and Here to Stay)!
+** "CPAN is my programming language of choice; the rest is just syntax."

+* 8000+ modules, 2500+ authors
** Automatic download, test and install
** Smoke testing, issue tracking, cross-reference, ratings...

+* CPAN is the greatest thing ever happened to Perl
+** ...However, heavy taxation from Perl 5 really hurts

----
== Language Tax on CPAN Users

* Sigils and references don't match:

    $s          @a      %h      
+    $$s         $a[0]   $h{'!'} 
+    $s->method  ☹       ☹

+* Forced redundancy:

    sub render {
        my $self = shift;
        my %opts = @_;
        foreach my $item ($self->filter(@{$self->{_items}})) {
            print "* @{[$item->draw($@opts{qw( x y z )})]}...\n";
        }
    }

----
== Fast forward to Perl 6...

* Sigils and references work just fine:

    $s          @a          %h      
+    $$s         @a[0]       %h{'!'} 
+    $s.method   @a.method   %h.method

+* Clean and simple semantics:

    method render (+$x, +$y, +$z) {
        for ./filter(@.items) {
            say .draw($x, $y, $z).as('* %s...');
        }
    }

----
== Implementation Tax on CPAN Authors

{image: http://perlcabal.org/~autrijus/images/jenga_home_prod.jpg}

* XS is difficult to write and maintain
+* Backward compatibility leaves little wiggle room
+* Hence, the Jenga architecture of /re(ab)use/
+* Macro programming sucks: Source filter and `eval ""`
+* Micro programming sucks: GC, threads, number crunch...
+* Arbitrary limitations on regex, operators, grammar, etc.
+* OO and functional code are unfairly handicapped in Golf ;-)

----
== Fast forward to Perl 6...

* Faster: JIT compiled; run in embedded machines
+* Friendlier: Call Perl5/C/Tcl/Python libraries directly
+* Easier: Common usage patterns dramatically shortened
+* Stronger: Support for OO, Functional, Data-driven styles
+* Leaner: Sane semantics instead of endless (documented) workarounds
+* Nicer: Fewer incomplete unmaintainable XS subsystems
+* DWIMmier: User-defined operators, syntax, grammars....

----
== Without further ado...

{image: http://perlcabal.org/~autrijus/images/cpan.jpg}

* We present: `cpan-upload.p6`!

    use AppConfig::Std--perl5;
    use Net::FTP--perl5;
    use HTTP::Request::Common--perl5;
    use LWP::UserAgent--perl5;
    use HTTP::Status--perl5;
    use File::Basename--perl5;

----
== Assimilating CPAN

{image: http://perlcabal.org/~autrijus/images/borg.jpg}

* The first batch of Perl 5 programs looked like that:

    require 'open3.pl';
    require 'bigint.pl';
    require 'my_library.pl';

+* Why can't we write our first Perl 6 programs like this?

    use DBI--perl5;
    use Template--perl5;

* Pugs's speed becomes less of an issue then.

----
== "Never do live demo!"

{image: http://perlcabal.org/~autrijus/images/murphy.jpg}

* Math:    mandel
* Network: http-server
* Obfu:    ipw-japh
* Games:   hangman
* WWW:     mod_pugs
* Prelude.pm!

----
== Upcoming: Catalyst on Pugs!

{image: http://perlcabal.org/~autrijus/images/catalyst.png}

* sri started working on it two weeks ago

    <sri> Perl 6 is damn sexy
    <sri> Perl 5 is a horrible hack
    <autrijus> It's a damn sexy hack, though
    <sri> True, but still a hack

+* Two days later, lathos started to port Maypole to Pugs

    <lathos> I'm actually *really* enjoying porting Maypole to Perl 6.
    <lathos> SO much cleaner.

+* Lots of dependencies were ported during the course:
** `Text::Glob`, `File::Find`, `FindBin.pm`, etc...
+* More yet to come.
** e.g., first draft of `POE.pm` arrived yesterday!

----
== Obligatory timeline picture

{image: http://pugscode.org/perl6-timeline.png}

* I'll show quick walkthrough of Perl 6 features
+** Mostly taken from Allison Randal's /Perl 6 Update/
** All of them are ready to run in Pugs!

----
== Simplicity

{image: http://perlcabal.org/~autrijus/images/huffman.jpg}

* Huffman coding makes easy things easy:

    say "Hello, World!" if $x == any(1..3);
    sub unfinished { ... }
    class Dog is Animal { has $.tail }

+* Easier to tell different constructs apart:

    eval "..." / try { ... }
    for @a { ... } / loop (;;) { ... }
    sub a { ... } / method b { ... }

----
== Sigils

{image: http://perlcabal.org/~autrijus/images/sigil.jpg}

* Consistent use of sigils:

    $scalar, @array, %hash
    @array[3]       # _not_ $array[3]
    %hash{'key'}    # also as %hash<key>

+* Hence hashes and arrays take methods too!

    %hash.keys
    @array.sort

----
== Dot

{image: http://perlcabal.org/~autrijus/images/dots.jpg}

* Compress three keystrokes to one:

    $obj.method()
    $a_ref.[1]      # also as $a_ref[1]
    $h_ref.<key>    # $h_ref<key>, $h_ref{'key'}
    $c_ref.()       # $c_ref()

+* There's more than one way to call it:

    say("Hello, World!");   # this works
    "Hello, World!".say;    # this too

----
== Methods

* Much more meaningful:

    @array.elems    # _not_ scalar(@array)
    $string.chars   # _not_ length($string)
    $string.bytes   # _not_ bytes::length($string)
    &function.arity # ... try doing this in Perl 5. ;)

* Easier to remember, too

----
== Named operators

* Lots of named variables:

    sub clean ($text, $method) { ... }          # by address
    sub by_value ($text is copy) { ... }        # by value
    sub some_opt ($req, ?$opt = $req) { ... }   # optional
    sub modify ($text is rw) { ... }            # writable
    sub typed (Int $num, Str $txt) { ... }      # typed

+* Available as Perl6::Subs in a CPAN near you!

+* The old way still works:

    sub sum {
        my $sum;
        $sum += $_ for @_;
        return $sum;
    }

----
== Higher-order functions

{image: http://perlcabal.org/~autrijus/images/hop.jpg}

* Currying with &code.assuming:

    sub times ($x, $y) { $x * $y }
    $sixtimes = &times.assuming(:y(6));
    $sixtimes(9); # 54

+* Implicit parameters:

    sub distance { sqrt( $^a ** 2 + $^b ** 2 ) }
    @array.sort:{ $^y <=> $^x };

----
== Multi Method Dispatch

* Type-based dispatch:

    multi sub add (Int $a, Int $b) { ... }
    multi sub add (Num $a, Num $b) { ... }
    multi sub add (Str $a, Str $b) { ... }

+* Operators are all multisubs by default:

    multi sub infix:«<» (Set $one, Set $two) returns Bool {
        $one.proper_subset($two);
    }

----
== Operators

* New operators:

    say =<README.txt>;  # &prefix:<=> := slurp()
    ...; !!!; ???;      # yada yada yada

+* Unicode operators

    sub prefix:<Σ>  (@x) { sum(@x) }
    sub postfix:<!> ($n) { ($n < 2) ?? 1 :: $n * ($n-1)! }
    say( Σ 1..5! );             # 7260
    (1, 2) ¥ ('a', 'b');        # (1, 'a', 2, 'b')

+* Chained operators 

    if $x > $y > $z { ... }
    if -r -w 'file' { ... }

----
== Strings

* Tilde replaces dot for string concatenation:

    $line = "Blue" ~ $moon;

+* But you won't miss the dot, because interpolation now works great:

    "Hello, $person";
    "You can call &subs() and $obj.methods() too!";
    "The attribute is %obj.keys.sort.reverse().";
    "Two plus Two is just { 2 + 2 }.";

+* Easy access to sprintf() with .as

    $string.as('Hello, %10s');

----
== Logic operators

{image: http://perlcabal.org/~autrijus/images/boolean.jpg}

* Short circuiting:

    $var  = 9 || 3; # 9

+* Boolean, numeric and bitwise logic:

    $bool = 9 ?| 3; # bool::true
    $true = 9 +| 3; # 11
    $bits = 9 ~| 3; # ";"

+* Skewed || means "defined or"

    $arg //= 3;
    $fh = open('file') err die $!;

----
== Hyper operators

{image: http://perlcabal.org/~autrijus/images/hyper.jpg}

* Hyperised binary operators:

    (1,1,2,3,5) »+« (1,2,3,5,8);  # (2,3,5,8,13)

+* Hyperised unary operators:

    -« (1,2,3); # (-1, -2, -3)

+* Autopromoted dimensions

    ('a'..'c') »x« 3;   # ('aaa', 'bbb', 'ccc')

----
== Reduction operators

    [+]                    # sum(...)
    [*]                    # product
    [*] 1..$x              # factorial
    [~]                    # join('', ...)
    [<]                    # monotony
    [==]                   # equality
    [//]                   # first defined element
    [||]                   # first true element
    [=>]                   # linked list construction

----
== Junctions

* Useful for common shorthands

    $options = '--help' | '-d' | '-e';
    if all($x, $y, $z) eq $options { ... }

+* The equivalent Perl 5 code:

    if (($x eq "--help" || $x eq "-d" || $x eq "-e") and
        ($y eq "--help" || $y eq "-d" || $y eq "-e") and
        ($z eq "--help" || $z eq "-d" || $z eq "-e")) { ... }

+* Test for prime numbers

    sub is_prime (Int $n) { $n % all(2 .. sqrt($n)+1) }
    sub has_twin (Int $n) { is_prime($n & ($n + (2 | -2))) }

----
== Aliasing

* There are no globs anymore

    &alias := &sub;
    $alias := $scalar;
    @alias := @array;

+* Aliasing a single container

    $alias := @array[2]{'many'}{'keys'};

+* Aliasing at BEGIN time:

    my $PI ::= 355/113;

----
== Smart Match

* `=~` is now spelled as `~~`:

    $value  ~~ /blue/;
    $value  ~~ s/x/y/;
    $value  ~~ rx:P5/blue/;

* But works for other cases too:

    $string ~~ any(<a b c d>);
    $obj    ~~ Class;

----
== Switch Statements

{image: http://perlcabal.org/~autrijus/images/switch.jpg}

* `given`/`when` uses the same way to match things:

    given $string {
        when all(/foo/, /bar/)  { ... }
        when .is_very_long      { ... }
        default                 { ... }
    }

+* You can use `given` by itself:

    given $very.complex.object {
        .method1;
        .method2;
    }

----
== Loops

{image: http://perlcabal.org/~autrijus/images/loop.jpg}

* `foreach` is now spelled `for`

    for @people -> $person {
        say "Hello, $person";
    }

+* `for` can loop over multiple variables

    for %ages.kv -> $name, $age {
        say "$name is now $age";
    }
    for zip(@a,@b) -> $a, $b {
        say "Are you $a or $b?";
    }

----
== Exceptions

{image: http://perlcabal.org/~autrijus/images/error.png}

* `$!` supercedes `$@`, `$?`, `$^E`

    system('rm -rf /') err die $!;

+* `eval {}` is now `try {}`

    try {
        may_throw_exception();
        CATCH { when Error::Nasty {...} }
    }

----
== Classes

* Declarations

    class Tree { method nodes { ... } }

+* Inheritance

    class Leaf is Tree {
        has $.val;
        method nodes { .val }
    }

+* Initialisation

    method BUILD ($.x, ?$.y = $.x)

----
== Attributes

* `has $.val` provides accessors automatically

    my $x = Leaf.new(:val<Hello>);
    say $x.val;     # "Hello"

+* Typed attributes:

    class Branch is Tree {
        has Tree $.left;
        has Tree $.right;
        method nodes { (nodes .left, nodes .right) }
    }

----
== Rules

{image: http://perlcabal.org/~autrijus/images/rulers.jpg}

* The same `m//`, `s///`, `//` syntax as Perl 5

    if $text ~~ /blue/ {...}
    $name ~~ s/Dan/Chip/;
    m:perl5/(\()?[^()]+(?(1)\))/;

+* Postfix modifiers moved to front of string

    s:g/a/b/
    m:P5<ism>/^yes.../

+* Space and comments are ignored by default (just like Perl 5's //x):

    m{ Larry    # perl6
     | Chip     # parrot
     | Autrijus # pugs
     };

----
== New Rules Syntax

* qr// is now rx//

    $myrule = rx/[yn]/

+* Anonymous and named rules

    $myrule = rule {\w\s+\w}
    rule myrule {\w\s+\w}

+* Rules may contain other rules

    rule name { Larry | Chip | Autrijus }
    rule project { perl6 | parrot | pugs }
    rule description :w { <name> does this <project> }

----
== Grammar

{image: http://perlcabal.org/~autrijus/images/grammar.jpg}

* Grammars are classes that contains rules

+* Provides a name for rules

    grammar URI { 
        rule reserved   { <[;/?:@&=+$,\[\]]>               };
        rule mark       { <[-_.!~*'()]>                    };
        rule unreserved { <[A-Za-z0-9]+<mark>>             };
        rule scheme     { <[a-zA-Z]><[a-zA-Z0-9.+-]>*      };
        rule uri        { <+<reserved>+<unreserved>+["%"]> };
    }

+* Perl 6 itself is a grammar too!

    grammar Perl6 { 
        rule statement { ... }
        rule identifier { ... }
    }

----
== Principles

{image: http://perlcabal.org/~autrijus/images/pearl.jpg}

* Simple...
+** ...but capable
+* Hybrid...
+** ...but distinct
+* Useful now...
+** ...and relevant then
+* Make Perl more Perlish

----
== Pugs

{image: http://linide.sourceforge.net/pugs-svngraph-6.2.5.png}

* So, what's this Pugs thing, really?

----
== Download and install

* 6.2.7: To be released today!

    http://pugscode.org/
    http://search.cpan.org/dist/Perl6-Pugs/

+* You need to install GHC 6.4 first:

    http://haskell.org/ghc/download.html

+* Or just burn the Live CD:

    http://linide.sourceforge.net/pugs-livecd-latest.iso

+* Check out the repository:

    % svk co http://svn.openfoundry.org/pugs
    % cd pugs
    % perl Makefile.PL
    % make; make test; make install

----
== History

{image: http://perlcabal.org/~autrijus/images/justdoit.jpg}

* Started at Feb 1st; 4 months old now
+* Self-inflicted TaPL exercise in Haskell
** Haskell cannot be taught; it must be learned
** See the perl.com interview for details
+* Extremely fast development
** A working interpreter in 6 days
** Test.pm runs correctly in 3 weeks

----
== Pugs the Interpreter

* Command line

    % pugs -e "'Hello, world!'.say"
    Hello, world!

    % pugs examples/japh/ipw-japh.p6
    Just another Perl6 hacker...

+* Interactive mode

    % pugs
    pugs> { $_ ?? $_ * &?BLOCK( $_ - 1 ) :: 1 }.(10)
    3628800

----
== Pugs the Compiler

* Make stand-alone binaries:

    % pugscc examples/hanoi.p6
    % pugscc --haskell -e "'Hello, world!'.say"
    % pugscc --parrot examples/mandel.p6

+* Compile and run in a single step:

    % pugs -Bparrot examples/mandel.p6

----
== Pugs the Anarchistic Community

{image: http://perlcabal.org/~autrijus/images/anarchism.jpg}

* Wiki-style development
+* To become a Pugs committer, you just need to:
** Commit stuff ;)
** Keep an eye on #perl6 and perl6-compiler
+* Test first
+* JFDI, based on Perl6::Bible
** Unspecified features: t/unspecced/
+* Average one more contributor every day

----
== Documentation

* The Canon: Perl6::Bible on CPAN
+* Quick references: docs/quickref/
+* Pugs Apocrypha
** PA01: Overview
** PA02: Internals
+* Perl 6 Cookbook: examples/cookbook/
+* Presentations and papers: docs/talks/
+** ...help wanted for my Haskell Workshop '05 paper :-)

----
== Tests

{image: http://perlcabal.org/~autrijus/images/checklist.jpg}

* We have 7200+ unit tests now
+* Test.pm is really simple to use
+* The smoke graph lists TODOs and regressions:

    file:///home/autrijus/work/release/pugs/util/graph.html

+* It's a coding monkey's paradise!

----
== Libraries

* Foreign:
** CPAN modules
** Parrot modules
** Haskell modules
+* Native:

Algorithm-TokenBucket Benchmark CGI Config-Tiny Date File-Find
File-Spec FindBin HTML-Entities Kwid-Event-Parser Locale-KeyedText
Net-IRC POE Perl-MetaModel Pod-Event-Parser Set Test Test-Builder
Text-Glob Tree fp lib libwww-perl

----
== Use Pugs in Perl 5 code

{image: http://perlcabal.org/~autrijus/images/yinyang.jpg}

    #!/usr/bin/perl

    use pugs;   # Here is some Perl 6 code...
    sub postfix:<!> { [*] 1..$_ }
    sub sum_factorial { [+] 0..$_! }

    no pugs;    # Here is some Perl 5 code...
    print sum_factorial(3); # 21

----
== From 6.0.* to 6.2.*

{image: http://perlcabal.org/~autrijus/images/smallpugs.jpg}

* Basic IO and control flow elements
+* Mutable variables
+* Assignment and aliasing
+* Compiling and embedding interface

----
== OO core: 6.28.*

{image: http://perlcabal.org/~autrijus/images/mediumpugs.jpg}

* Classes and Objects
+* Inheritance
+* Subtyping
+* Introspection # /TODO/
+* Roles # /TODO/

----
== Rules core: 6.283.*

{image: http://perlcabal.org/~autrijus/images/bigpugs.jpg}

* Match/substitution with rules
+* Named and nested captures
+* Closures in rules # /TODO/
+* Grammar classes # /TODO/

----
== Approximating /2π/

{image: http://perlcabal.org/~autrijus/images/web.jpg}

* 6.2831
** Role composition
** Fully specified runtime semantics
+* 6.28318
** Macros!
+* 6.283185
** Port Pugs to Perl 6
** Finish bootstrapping

----
== Pugs: Join the fun!

{image: http://perlcabal.org/~autrijus/images/woodstock.jpg}

* Port modules
+* Contribute examples
+* Write tests
+* Document the implementation
+* Learn Haskell, hack on Pugs internals
+* Let's build the new ship together!

----
== Bonus Revelations

{image: http://perlcabal.org/~autrijus/images/apoc.jpg}

* Imminent
+** Amazingly
+*** Great
+**** Stuff!

----
== Software Transaction Memory

{image: http://perlcabal.org/~autrijus/images/mememto.jpg}

* Classical race condition:

    my $a is shared = 1;
    async { my $b = $a; $a = $b + 1 };
    async { my $c = $a; $a = $c + 1 };
    say $a;     # 2? 3?

+* It's either deadlocks, or huge `select()` loops

+* Now solved with automatic rollback:

    atomically { my $b = $a; $a = $b + 1 }
    atomically { my $c = $a; $a = $c + 1 }

+* Implemented in Java, C#, Fortress, GHC...
+* Pugs has switched to STM storage
** No noticeable performance penalty
+** Would be really nice for Perl 6 to have it

----
== Serialised Continuations

{image: http://perlcabal.org/~autrijus/images/back2future.jpg}

* What if `dump()` works reliably...
+** Anywhere in your program
+** On part of the stack
+** And produces really small images?
+* No need for web sessions anymore
+** Just save the application state in forms and cookies
+** Multi-step control flow becomes trivial
+* Omniscient debugging
+** Go back and forth in time
+** Not only observe, but modify the program in real-time
+* Many more applications: clustering, mobile code, etc...

----
== Pugs on Parrot!

{image: http://perlcabal.org/~autrijus/images/parrotpugs.jpg}

* Pugs can compile `mandel.p6` and `mod_pugs` to Parrot
+** ...but that's the only two things that works now
+* Parrot runs `mandel.p6` about 100x faster than Pugs
** ...  even faster than Perl 5 if we use unboxed types, 
+* Leo and Chip will be talking about Parrot in a bit
** We'll stay at Leo's place for the next 10 days
+* Merge Pugs's interpreter core with PAST
+* Watch my use.perl journal for updates!

----
== Thank you!

{image: http://perlcabal.org/~autrijus/images/bowing.jpg}

* Any questions?

