lecture
in color
sub foo { 2*$_[0] }
my sub foo (Int $num) returns Int { 2*$num }
@a = (1,2);
sub foo { return $_[0]+$_[1] }
foo(@a);
@a = (1,2);
sub foo (Int $n, Int $m) { return $n+$m }
foo(*@a); # foo(@a) is syntax error
my %stuff;
my sub foo: lvalue { $_[0]->{$_[1]} }
my STRING method ($thing: $name) is rw { $thing{$name} }
# regularized!
sub foo;
sub foo (Int $num) returns Int { ... }
Access through... Perl 5 Perl 6
================= ====== ======
Scalar variable $foo $foo
Array variable $foo[$n] @foo[$n]
Hash variable $foo{$k} %foo{$k}
Array reference $foo->[$n] $foo.[$n] (or $foo[$n])
Hash reference $foo->{$k} $foo.{$k} (or $foo{$k})
Code reference $foo->(@a) $foo.(@a) (or $foo(@a))
Array slice @foo[@ns] @foo[@ns]
Hash slice @foo{@ks} %foo{@ks}
(source: http://dev.perl.org/perl6/exegesis/2)
->, enter ., confuse people who think . is for strings!
print $x; # $x evaluates to scalar
print $y[1]; # $y[1] evaluates to scalar
print $z{a}; # $z{a} evaluates to scalar
print $yref->[1]; # $yref->[1] evaluates to scalar
print $zref->{a}; # $zref->{a} evaluates to scalar
print @y; # @y evaluates to list
print @y[2,3]; # @y[2,3] evaluates to list
print @z{'b','c'}; # @z{'b','c'} evaluates to list
print @{$yref}[2,3]; # @{$yref}[2,3] evaluates to list
print @{$zref}{'b','c'}; # @{zyref}{'b','c'} evaluates to list
print %z; # %z evaluates to hash
(source: http://dev.perl.org/perl6/exegesis/2)
_'; yes, space is part of the
operator! So that $a _ $b is their concatenation, and $a_$b means perhaps something else! For example:
# Perl 6 code # Meaning in Perl 5 $name = getTitle _ getName; # getTitle() . getName() $name = getTitle_ getName; # getTitle_(getName()) $name = getTitle _getName; # getTitle(_getName()) $name = getTitle_getName; # getTitle_getName() (source: http://dev.perl.org/perl6/exegesis/3)
_@somethingis the string version of the contents of
@something!
print STDERR bar;becomes in perl6
print STDERR: bar;
sub cat { my $foo = shift; my $bar = shift; return $foo->{$bar} }
becomes, in perl6
sub cat ($foo: $bar) { return $foo.{$bar} }
if it is to be called via something like $foo.cat($bar).
Void context
Scalar context
Boolean context
Integer context
Numeric context
String context
Object context
List context
Flattening list context (true list context).
Non-flattening list context (list of scalars/objects)
Lazy list context (list of closures to be evaluated when needed)
Hash list context (list of pairs)
(This list isn't necessarily exhaustive.)
(source: http://dev.perl.org/perl6/exegesis/2)
while (@array) { ... }
evaluates @array in a boolean context, while
while (@array>0) { ... }
evaluates @array in a numeric context.
sub my_system ($shell_command) {
...
return $error is false if $error;
return 0 is true;
}
(source: http://dev.perl.org/perl6/exegesis/2)
If you do this, then
if (&my_system(...)) { ... }
will interpret 0 as true and nonzero as false in a boolean context!
my Array $x;means that
$x is a reference to Array. It's a promise not to use $x in any other way, which allows the compiler to optimize references.
my Int $x;declares a scalar Perl integer (with all the attributes of a Perl value, e.g., tainting, etc) while
my int $x;declares a system integer that isn't a symbol. This can't be tainted, e.g.
INT or Int.
$x is Found(1);to give the scalar
$x a property Found (just like in LISP!) and even say things like
$x.Found($x.Found+1);to increment it.
int, have no property lists.
$h = \%hash;to get a reference to a thing.
$h = %hash;to achieve the same behavior.
:=
$foo = \${$bar->{'cat'}->{'dog'}};
and then refer to $$foo.
$foo := $bar.{cat}{dog};
anything you do to $foo also changes the RHS value.
$foo = $bar.{cat}{dog};
sets $foo to the value of $bar.{cat}{dog} so that changing $foo doesn't change $bar.{cat}{dog}.
sub: an uninheritable (private) subroutine with
a regular parameter list.
method: an inheritable (public) subroutine;
member of a class, invocant (class instance) as parameter.
submethod: an uninheritable (private) method;
same as a sub masquerading as a method. multi: multimethods: not a member of a particular class,
but has one or more possible invocants (class instance parameters).
macro: a real macro, expanded inline, not a subroutine.
my <RETTYPE> sub <NAME> (<PARAMS>) <TRAITS> { <CONTENT> }
our <RETTYPE> sub <NAME> (<PARAMS>) <TRAITS> { <CONTENT> }
sub <NAME> (<PARAMS>) <TRAITS> { <CONTENT> }
sub (<PARAMS>) <TRAITS> { <CONTENT> }
:lvalue.
sub say { print qq{"@_"\n}; } # WORKS: args appear in @_
sub cap { $_ = uc $_ for @_ } # ERROR: elements of @_ are constant
Note: Exegesis 2 says @_ is a normal Perl 5 argument list; Exegesis 6 says that @_ is const.
sub swap (*@_ is rw) { @_[0,1] = @_[1,0] }
# read: "elements of @_ are rw"
-> now synonym for sub
$sq = -> $val { $val**2 }; # Same as: $sq = sub ($val) { $val**2 };
for @list -> $elem { # Same as: for @list, sub ($elem) {
print "$elem\n"; # print "$elem\n";
} # }
sub blah;is a syntax error.
sub foo {...};
where ... is part of the syntax.
sub foo ($name, $adjective) { $name _ " is " _ $adjective }
method get ($self: $name ) { $self{$name} }
# regularization!
method set ($self: $name, $value) { $self{$name} = $value }
# regularization!
$obj.set('stuff', 1) ;
# yes, they changed the subroutine reference operator to |.|!
# here $obj becomes $self!
sub boo ($name, ?$title) {
if (defined $title) {
return "$name, $title";
} else {
return "$name";
}
sub boo ($name, ?$title = "student") {
return "$name, $title";
}
sub goo ($x,$y) { $x <=> $y }
print goo(x=>1, y=>2);
or, to force naming:
sub hoo (+$x,+$y) { $x <=> $y }
print hoo(x=>1, y=>2); # or hoo(y=>2, x=>1) !
sub expose($n, +$name, *$one, *@extra, *%named) {
print "n = $n\n";
print "name = $name\n";
print "one = $one\n";
print "extra = " _ join(' ',@extra);
while (($key,$value) = each %named) {
print "key $key => value $value\n";
}
}
expose(1,2,3,4,5,6,7,'name'=>'joe', 'number'=>5)
prints something like
n=1 name=joe one=2 extra=3 4 5 6 7 key number => value 5
*$one contains the next argument after $n, a *varadic scalar*.
*@extra contains extra undeclared, unnamed values other than
values bound to varadic scalars.
*%named contains extra undeclared, named values.
*@extra *replaces* @_. One can say
*@_ in the argument list for compatibility.
$n, +$m, *$foo, *@bar, *%blah
and your arguments are 'm'=>'goo', 1,2,'hoot'=>'joe',3 $m to goo. %blah.
=>. This is the old
@_, which is not defined if you declare an argument list. $n to 1. $foo to 2. *@bar to the remainder of
arguments. This sets @bar to (3).
sub head(*$head, *@tail) { return $head }
sub tail(*$head, *@tail) { return @tail }
Then
head(1,2,3,4,5)is
1 whiletail(1,2,3,4,5)is
(2,3,4,5).
arity method:
$args_required = &goo.arity;
sub my_substr ($str, ?$from, ?$len) {...}
"Flattening" arrays
@array => *@array.
sub doo ($a,$b) { $a _ $b }
@stuff = (1,2);
then
doo(@stuff)is a syntax error while
doo(*@stuff)calls it correctly. } stopped here last time
==> and <== pass variant arrays to functions
e.g., if
sub goo (*@data) { print join (' ', @data); }
then
goo <== @stuffand
@stuff ==> gooare shorthands for the more painful
goo (*@stuff)which is necessary because arrays aren't by default flattened as parameters.
@things = map { $_>=0 } <== grep { $_ % 2 == 0 } <== @stuff
or even
@things = @stuff ==> grep { $_ % 2 == 0 } ==> map { $_>=0 }
bit single native bit int native integer str native string num native floating point ref native pointer bool native boolean Bit Perl single bit (allows traits, aliasing, etc.) Int Perl integer (allows traits, aliasing, etc.) Str Perl string Num Perl number Ref Perl reference Bool Perl boolean Array Perl array Hash Perl hash IO Perl filehandle Code Base class for all executable objects Routine Base class for all nameable executable objects Sub Perl subroutine Method Perl method Submethod Perl subroutine acting like a method Macro Perl compile-time subroutine Rule Perl pattern Block Base class for all unnameable executable objects Bare Basic Perl block Parametric Basic Perl block with placeholder parameters Package Perl 5 compatible namespace Module Perl 6 standard namespace Class Perl 6 standard class namespace Object Perl 6 object Grammar Perl 6 pattern matching namespace List Perl list Lazy Lazily evaluated Perl list Eager Non-lazily evaluated Perl list
of, returns keywords.
my Cat $dog; my $dog returns Cat; my $dog of Cat;
our Cat sub pet() {...}
sub pet() returns Cat {...}
sub pet() of Cat {...}
my Dog @pound; my Rat %ship;
my $cat is Scalar; # default my $cat is PersistentScalar; my $cat is DataBase;
my Array of Student @class; my @class of Array of Student; my Hash of Array of Student %school;
my Int|String $thing; # either an Int or a String my Hash of Array of Student|Teacher %school;Gasp!
$*foo.
&*sub.
$*next_id = 0; # global variable
# global subroutine
sub *saith($text) { print "Yea verily, $text" }
module A {
my $next_id = 2; # hides any global or package $next_id
saith($next_id); # print the lexical $next_id;
saith($*next_id); # print the global $next_id;
}
module B {
saith($next_id); # Unambiguously the global $next_id
}
:lvalue replaced with is rw.
my $lastval;
sub lastval () is rw { return $lastval }
^ becomes ~ for binary xor.
^ is the hyper-operator; it vectorizes a normal operator.
@stuff = @foo ^+ @bar;computes the vector sum of
@foo and @bar
-> becomes .
. becomes _
prefix or postfix:
sub prefix:OPNAME ($operand) {...}
sub postfix:OPNAME ($operand) {...}
For example,
sub prefix:rant ($thing) { $thing " is soooo dumb!" }
print rant 'Perl 6';
prints
Perl 6 is soooo dumb!If you always wanted a factorial operator,
multi postfix:! (Int $n) { $n<2 ?? 1 :: $n*($n-1)! }
print 5! _ "\n";
infix.
sub infix:OPNAME ($leftop, $rightop) {...}
For example,
sub infix:poo ($left, $right) { $left _ ' excretes ' _ $right }
print "Perl 6" poo "hubris\n";
prints
Perl 6 excretes hubris
sub infix:(c) ($text, $owner) { return "$text copyright $owner" }
print "Perl 6" (c) "Larry Wall\n";
sub circumfix:LEFTDELIM...RIGHTDELIM ($contents) {...}
$contents are returned as a string. For example,
macro circumfix:<!--...--> ($text) { "" }
elides HTML comments!
sub circumfix:(begin)...(end) ($stuff) { eval $stuff }
(begin)print "hi there\n"; print "ho there\n"(end)
prints what you'd expect.
returns # declares return type is rw # implements call by reference is copied # forces explicit value copy is constant # declares a constant value is parsed # specifies parsing rule is cached # speeds name search is inline # treats as macro is tighter/is looser/is equiv # defines operator precedence! is assoc # defines associativity is PRE/POST # define precondition and postcondition guard blocks is FIRST/LAST/NEXT/KEEP/UNDO/etc. # unconditionally executed blocks
$file = rx/ ^ <$hunk>* $ /;is a rule that refers to a subrule
$hunk and interpolates it into the pattern. $file is the rule itself, not the expression that invokes it. x is turned on and whitespace doesn't matter.
$file = rx/ ^ <$hunk>* $ /; $hunk = rx :i {
[ <$linenum> a :: <$linerange> \n
<$appendline>+
|
<$linerange> d :: <$linenum> \n
<$deleteline>+
|
<$linerange> c :: <$linerange> \n
<$deleteline>+
--- \n
<$appendline>+
]
| (\N*) ::: { fail "Invalid diff hunk: $1" }
};
$linerange = rx/ <$linenum> , <$linenum> | <$linenum> /;
$linenum = rx/ \d+ /;
$deleteline = rx/^^ \< <sp> (\N* \n) /;
$appendline = rx/^^ \> <sp> (\N* \n) /;
# and later...
my $text is from($*ARGS);
print "Valid diff" if $text =~ /<$file>/;
(source: http://dev.perl.org/perl6/exegesis/5)
<$var> is evaluated at
match time, rather than expression compile-time.
PRIME CHARACTER ==> CREATIVE IDEA ==>
COUNTER-CULTURE ==> SUBCULTURE ==> EVOLUTION
(source: Gordon Dickson, Foreword to "Three to Dorsai")
(Yes, he did typeset this, in almost these exact words,
using the then-to-be Perl 6 pipe operator ==>!)
lecture
in color