Perl 6

Se vc sabe Perl 5, este link é delicioso

http://perlgeek.de/en/article/5-to-6

senão conhece, vale ler

http://www.perl6.org/documentation/

A evolução da linguagem faz sentido. É claro que, se vc acha estranho preceder variáveis por um $ (ou arrays de @ e hashes de %) porém se no passado isso ajudou o interpretador hoje faz parte do idioma. O fato é que a linguagem ousa unir todos os paradigmas além de prover mecanismos para alterar a sua própria linguagem, lazyness, e por ai vai.

Vou colocar alguns exemplos interessantes. A linguagem tem MUITO ruído e isso não vai mudar (comparando com ruby, que é perfeito para alguns tipos de DSLs) porém basta pratica.

Basic Control Structures

    if $percent > 100  {
        say "weird mathematics";
    }
    for 1..3 {
        # using $_ as loop variable
        say 2 * $_;
    }
    for 1..3 -> $x {
        # with explicit loop variable
        say 2 * $x;
    }

    while $stuff.is_wrong {
        $stuff.try_to_make_right;
    }

    die "Access denied" unless $password eq "Secret";

You can also use more than one loop variable:

for 0..5 -> $even, $odd { say "Even: $even \t Odd: $odd"; }

Multi Subs - coisa que sinto falta em algumas linguagens :slight_smile:

[code] multi sub my_substr($str) { … } # 1
multi sub my_substr($str, $start) { … } # 2
multi sub my_substr($str, $start, $end) { … } # 3
multi sub my_substr($str, $start, $end, $subst) { … } # 4

multi sub frob(Str $s) { say "Frobbing String $s"  }
multi sub frob(Int $i) { say "Frobbing Integer $i" }

frob("x")       # Frobbing String x
frob(2)         # Frobbing Integer 2

[/code]

Objects and Classes:

Apresentando as Roles, que lembram as Interfaces/Modulos/Classes Abstratas

[code] role Paintable {
has $.colour is rw;
method paint { … }
}
class Shape {
method area { … }
}

class Rectangle is Shape does Paintable {
    has $.width;
    has $.height;
    method area {
        $!width * $!height;
    }
}[/code]

Regexes

grammar URL { token TOP { <schema> '://' [<hostname> | <ip> ] [ ':' <port>]? '/' <path>? } token byte { (\d**{1..3}) <?{ $0 < 256 }> } token ip { <byte> [\. <byte> ] ** 3 } token schema { \w+ } token host { (\w+) ( \. \w+ )* } token port { \d+ } token path { <[ a..z A..Z 0..9 -_.!~*'():@&=+$,/ ]>+ } }

Junctions - inspirado na mecanica quantica!!

[code] if $x eq 3|4 {
say ‘$x is either 3 or 4’
}
say ((2|3|4)+7).perl # (9|10|11)

my @items = get_data();
if all(@items) >= 0 { ... }

[/code]

Ja citada Laziness

[code] my @integers = 0…*;
for @integers -> $i {
say $i;
last if $i % 17 == 0;
}

my @even = map { 2 * $_ }, 0..*;
my @stuff = gather {
    for 0 .. Inf {
        take 2 ** $_;
    }
}[/code]

Em especial

[quote]Controlling Laziness
Laziness has its problems (and when you try to learn Haskell you’ll notice how weird their IO system is because Haskell is both lazy and free of side effects), and sometimes you don’t want stuff to be lazy. In this case you can just prefix it with eager.

On the other hand only lists are lazy by default. But you can also make lazy scalars:

Custom Operators

[code] multi sub postfix:<!>(Int $x) {
my $factorial = 1;
$factorial *= $_ for 2…$x;
return $factorial;
}

say 5!;                     # 120[/code]

Subset types

[code] subset Squares of Int where { .sqrt.int**2 == $_ };

multi sub square_root(Squares $x --> Int) {
    return $x.sqrt.int;
}
multi sub square_root(Num $x --> Num) {
    return $x.sqrt;
}[/code]

Por fim, a sub MAIN

[code] # file doit.pl

#!/usr/bin/perl6
sub MAIN($path, :$force, :$recursive, :$home = glob("~/")) {
# do stuff here
}

command line

$ ./doit.pl --force --home=/home/someoneelse file_to_process[/code]

Se alguem quiser se aventurar, sugiro entrar nas listas de perl, baixar o Rakudo que é a implementação mais completa até o momento e usar, por exemplo, a IDE chamada PADRE.

De fato Perl sempre abusou de operadores (não seria de admirar que ampliaram as expressões regulares), por outro lado a evolução para a versão 6 é absurda. Uma linguagem imperativa que tem suporte a laziness, por exemplo, é fantástico. Some ao fato que a linguagem suporta 3 formatos de goto

[code]goto LABEL

goto EXPR

goto &NAME[/code]

The first form causes the current execution point to jump to the point referred to as LABEL. A goto in this form cannot be used to jump into a loop or external function.you can only jump to a point within the same scope.

The second form expects EXPR to evaluate to a recognizable LABEL. In general, you should be able to use a normal conditional statement or function to control the execution of a program, so its use is deprecated.

(minha favorita) The third form substitutes a call to the named subroutine for the currently running subroutine. The new subroutine inherits the argument stack and other features of the original subroutine; it becomes impossible for the new subroutine even to know that it was called by another name.

Se com C é fácil dar tiros no pé, com Perl vc faz uso do próprio Darth Vader.

Agora, isto é divertido++

[quote]Perl 6 embraces the idea of multi threading, and in particular automated parallelization. To make sure that not all threads suffer from the termination of a single thread, a kind of “soft” exception was invented.

When a function calls fail($obj), it returns a special value of undef, which contains the payload $obj (usually an error message) and the back trace (file name and line number). Processing that special undefined value without check if it’s undefined causes a normal exception to be thrown.

[code]my @files = </etc/passwd /etc/shadow nonexisting>;
my @handles = hyper map { open($_) }, @files;[/code]

In this example the hyper operator tells map to parallelize its actions as far as possible. When the opening of the nonexisting file fails, an ordinary die “No such file or directory” would also abort the execution of all other open operations. But since a failed open calls fail(“No such file or directory” instead, it gives the caller the possibility to check the contents of @handles, and it still has access to the full error message.

If you don’t like soft exceptions, you say use fatal; at the start of the program and cause all exceptions from fail() to be thrown immediately.[/quote]

Lembra alguma coisa? Hehe.