Learning Perl 6
   brian d foy, <brian@stonehenge.com>
  Version 0.6, Nordic Perl Workshop 2007
for the purposes of this tutorial




 Perl 5
 never
existed
Don’t really do this
$ ln -s /usr/local/bin/pugs /usr/bin/perl
Introduction
It’s a completely new language
That other one never existed
Llama 6 is a long way off
This is the basics of t...
Basis for this talk
Apocalypses
Exegeses
Synopses
Perl6-Pugs-N-NN
 docs/quickref/data
 examples/
Actual Pugs behavior
Writing programs
you can actually
      run
In 30 minutes, I can cover

  Data
  Variables
  Control structures
  Input / Output
If I had more time

Subroutines
Regular expressions
Using modules
Creating classes, objects, &c.
Getting Pugs
http://www.pugscode.org
Needs Glasgow Haskell Compiler (GHC)
Get the binary builds
 compilation can take a lo...
Making a P6 program
Programs are just text files
Syntax is C like, mostly
 whitespace is not significant, mostly
 statements...
Objects & Methods
Data are objects or nouns
Methods are verbs (actions)
Object.Method

 #!/usr/local/bin/pugs

 quot;Hello...
Run from command line
  $ pugs hello.p6
  Hello World

  $ ./hello.p6
  Hello World

  $ pugs -e 'say quot;Hello Worldquot...
Scalars
Scalars are single values

        Numbers

         Strings

        Boolean
Literal numbers
3 3.14 3.14e7 -4.56 0

       123_456

       0b0110

     0o377 0o644

  0xAB 0xDEAD_BEEF
say
say can be used a method
Outputs the value and tacks on a newline
More output stuff later

   quot;Hello Worldquot;.sa...
Arithmetic

2   + 3           5
2   - 3           -1
2   * 3           6
2   / 3           0.66666666...
2   ** 3         ...
Method call forms
# indirect form
say 3;

# direct form
3.say;

# parens to group
( 10 / 3 ).say;

# / really just a metho...
Strings


Sequence of zero or more characters
Perl inter-converts automatically with
numbers
Single quoted strings
'Hello World'.say;

'I said 'Hello World!''.say;

'I need a literal '.say;

q/I don't need to escape...
Double quoted strings
quot;HellotWorldquot;.say;

quot;I said quot;Hello World!quot;quot;.say;

quot;Hello Worldquot;.prin...
String concatenation
   ~ stitches strings together
( quot;Helloquot; ~ quot;Worldquot; ).say;
HelloWorld

( quot;Helloquo...
String replication
      x repeats and joins string
( quot;Hiquot; x 3 ).say;        HiHiHi

( quot;Hiquot; x 2.5 ).say;  ...
Booleans


True or False, Yes or No, On or Off, 1 or nothing
Often the result of a comparison
Numeric comparisons
5    <   6   True
5    >   6   False
5   ==   6   False
5   <=   6   True
5   >=   6   False
5   !=   ...
String comparisons

'fred'   lt   'barney'   False
'fred'   gt   'barney'   True
'fred'   eq   'barney'   False
'fred'   l...
Scalar variables
Stores a single value
Name starts with a letter or underscore,
followed by letters, underscores, or digit...
Scalar Assignment

my $num = 5;
quot;The number is $numquot;.say;

my $str = quot;Pugsquot;;
quot;Just another $str hacker...
Scalar value type
The ref method gives the type of scalar
 my   $s1   =   5 < 6;
 my   $s2   =   quot;Perlquot;;
 my   $s3...
Standard input

quot;Enter a name> quot;.print;
my $input = (=$*IN).chomp;

quot;Enter another name> quot;.print;
$input =...
Control Structures
if-elsif-else
if 5 < 6   { quot;5 less than 6quot;.say }


if 5 > 6   { quot;5 more than 6quot;.say }
else       { quot;5 ...
Complex comparisons
if( 5 < $x < 10 )
  {
  quot;$x is between 5 and 10quot;.say
  }
else
  {
  quot;$x is not between 5 a...
Junctions
my $num   = 5;

if( $num == any( <5 6 7> ) )
  {
  quot;$num is in the setquot;.say
  }
else
  {
  quot;$num is ...
Expression modifiers
Apply a condition to a single expression


quot;5 is greaterquot;.say if 5 > 6;

quot;5 is lessquot;.s...
loop
loop ( init; test; increment ){ }

loop ( $i = 1; $i < 10; $i++ ) {
  quot;I can count to $iquot;.say;
  }
   I can  ...
next
   skips the rest of the block
   goes to next iteration
loop ( $i = 1;    $i < 10; $i++ ) {
  next if $i %    2;
  q...
last
   skips the rest of the iterations
   continues after the loop

loop ( $i = 1; $i < 10; $i++ ) {
  last if $i == 5;
...
redo
   starts the current iteration again
   uses the same element (if any)

loop {
  quot;Do you like pugs?> quot;.print...
Number guesser
quot;Guess secret number from 1 to 10quot;.say;
my $secret = rand(10+1).int;

loop {
  quot;Enter your gues...
Lists & Arrays
Literal Lists
( 1, 2, 3, 4 )

  <a b c d>

 my $x = 'baz'
<<foo bar $x>>
  «foo bar $x»

  ( 1 .. 3 )
( 'a' .. 'z' )
List replication
'f'   xx 4       <f f f f>

<g> xx 6         <g g g g g g>

< a b c > xx 2   < a b c a b c >
Joining elements

<1 2 3 4>.join(' ')   1 2 3 4

<1 3 5 7>.join(':')   1:3:5:7
Ranges
( 4 .. 7 )           < 4 5 6 7 >

( 'a' .. 'e' )       < a b c d e >

reverse 1 .. 3       < 3 2 1 >

( 1 .. 3 ).re...
Arrays
Array variables store multiple scalars
Indexes list with integers, starting at 0
Same variable naming rules as a sc...
Array assignment

my @a = < a b c >;

my @a = << a b $c >>

my @a = 1 .. 6;
Bounds
my @r = 37..42;
say quot;Minimum is quot; ~ @r.min;
say quot;Maximum is quot; ~ @r.max;

my @a = < 3 5 9 2 5 0 1 8 ...
Array elements
my @a = <a b c d e f g>;

my $first = @a[0];         a

my $last   = @a[-1];       g

my $count = @a.elems;...
Unique elements


my @a = <a b c a b d b d>;

my @b = @a.uniq;   < a b c d >
Hyperoperators
    Apply operator pair wise
my @nums   =       1 .. 10;
my @alphas =      'a' .. 'j';

my @stitch = @nums ...
for
for 1 .. 5 -> $elem {
  quot;I saw $elemquot;.say;
  }

      I   saw   1
      I   saw   2
      I   saw   3
      I ...
for
for @ARGS -> $arg {
  quot;I saw $arg on the command linequot;.say;
  }


  I saw fred on the command line
  I saw bar...
Hashes
Hash variables
Hash variables stores unordered pairs
Index is the “key”, a unique string
Makes a map from one thing to ano...
Hash elements
my %h = <a 5 b 7 c 3>;

my $a_value = %h{'a'};    5

my $b_value = %h<b>;      7

my $count = %h.elems;     ...
my %hash = (
  'fred'   => 'flintstone',
  'barney' => 'rubble',
  );

%hash.say;
  barney rubblefred flintstone
%hash.joi...
Hash keys
my %hash = (
  'fred'   => 'flintstone',
  'barney' => 'rubble',
  );

for %hash.keys -> $key {
  quot;$key: %ha...
Hash values
my %hash = (
  'fred'   => 'flintstone',
  'barney' => 'rubble',
  );

for %hash.values -> $value {
  quot;One...
By pairs
my %hash = (
  'fred'   => 'flintstone',
  'barney' => 'rubble',
  );

for %hash.kv -> $key, $value {
  quot;$key...
Counting words
my %words;

for =<> -> $line {
  for $line.chomp.split -> $word {
    %words{$word}++;
    }
  }

for %word...
exists
      True if the key is in the hash
      Does not create the key

my @chars = <fred wilma barney betty>;

my %has...
delete
    Removes pair from hash
my %hash =   (
  'fred'     => 'flintstone',
  'barney'   => 'rubble',
  'dino'     => u...
Input
Output
Standard input
quot;Enter a name> quot;.print;
my $input = (=$*IN).chomp;

quot;Enter another name> quot;.print;
$input = ...
File input operator
The =<> reads from files from the
command line arguments

  for =<> -> $line {
    quot;Got $linequot;....
Opening files to read
my $fh = open( $file, :r );

for =$fh -> $line {
  quot;Got $linequot;.print;
  }
Die-ing
my $file = quot;not_therequot;;

my $fh = open( quot;not_therequot;, :r )
  err die quot;Couldn’t open $file: $!qu...
try
     Catches exceptions

try {
  die quot;I'm dyingquot; if time.int % 2;
  quot;I made itquot;.say;
  };

quot;Error ...
Standard filehandles
    Default filehandles $*OUT and $*ERR


$*ERR.say( quot;This goes to stderrquot; );

$*OUT.say( quot;...
Writing to files
my $file = quot;not_therequot;;

my $fh = open( quot;not_therequot;, :w )
  err die quot;Couldn’t open $fi...
try
     Catches exceptions

try {
  die quot;I'm dyingquot; if time.int % 2;
  quot;I made itquot;.say;
  };

quot;Error ...
Files and Directories
File tests
my $file = quot;file_tests.p6quot;;

quot;Found filequot;.say if $file ~~ :e;
quot;Readable filequot;.say if $f...
Other topics
given is like C’s switch (but better)

variable value types

complex data structures

regular expressions - PCRE and new s...
Summary

Perl 6 is a new language
It borrows from Perl (and ancestors)
It’s not done yet, but it’s almost usable
Upcoming SlideShare
Loading in...5
×

Learning Perl 6 (NPW 2007)

3,784

Published on

A very brief introduction to Perl 6 at the Nordic Perl Workshop 2007 in Copenhagen

Published in: Technology, Business
2 Comments
2 Likes
Statistics
Notes
  • It might not be anymore, but the slides are pretty old. Audrey Tang had looked over the slides before my talk and mentioned that it wasn't implemented as a method call in Pugs, but that didn't mean it shouldn't be. Most of the talk is pretty dated and probably half wrong now.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • 'say 3' isn't an indirect method call, is it? that would have to be written 'say: 3'
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
3,784
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
2
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Learning Perl 6 (NPW 2007)"

  1. 1. Learning Perl 6 brian d foy, <brian@stonehenge.com> Version 0.6, Nordic Perl Workshop 2007
  2. 2. for the purposes of this tutorial Perl 5 never existed
  3. 3. Don’t really do this $ ln -s /usr/local/bin/pugs /usr/bin/perl
  4. 4. Introduction It’s a completely new language That other one never existed Llama 6 is a long way off This is the basics of the language Next week it might be different
  5. 5. Basis for this talk Apocalypses Exegeses Synopses Perl6-Pugs-N-NN docs/quickref/data examples/ Actual Pugs behavior
  6. 6. Writing programs you can actually run
  7. 7. In 30 minutes, I can cover Data Variables Control structures Input / Output
  8. 8. If I had more time Subroutines Regular expressions Using modules Creating classes, objects, &c.
  9. 9. Getting Pugs http://www.pugscode.org Needs Glasgow Haskell Compiler (GHC) Get the binary builds compilation can take a long, long time and it eats up your CPU
  10. 10. Making a P6 program Programs are just text files Syntax is C like, mostly whitespace is not significant, mostly statements separated by semicolons comments are # to end of line Use pugs on the shebang line #!/usr/local/bin/pugs say quot;Hello Worldquot;;
  11. 11. Objects & Methods Data are objects or nouns Methods are verbs (actions) Object.Method #!/usr/local/bin/pugs quot;Hello Worldquot;.say;
  12. 12. Run from command line $ pugs hello.p6 Hello World $ ./hello.p6 Hello World $ pugs -e 'say quot;Hello Worldquot;' Hello World $ pugs pugs> say quot;Hello Worldquot; Hello World bool::true
  13. 13. Scalars
  14. 14. Scalars are single values Numbers Strings Boolean
  15. 15. Literal numbers 3 3.14 3.14e7 -4.56 0 123_456 0b0110 0o377 0o644 0xAB 0xDEAD_BEEF
  16. 16. say say can be used a method Outputs the value and tacks on a newline More output stuff later quot;Hello Worldquot;.say; say quot;Hello Worldquot;;
  17. 17. Arithmetic 2 + 3 5 2 - 3 -1 2 * 3 6 2 / 3 0.66666666... 2 ** 3 8 2 % 3 2
  18. 18. Method call forms # indirect form say 3; # direct form 3.say; # parens to group ( 10 / 3 ).say; # / really just a method (10./(3)).say;
  19. 19. Strings Sequence of zero or more characters Perl inter-converts automatically with numbers
  20. 20. Single quoted strings 'Hello World'.say; 'I said 'Hello World!''.say; 'I need a literal '.say; q/I don't need to escape/.say;
  21. 21. Double quoted strings quot;HellotWorldquot;.say; quot;I said quot;Hello World!quot;quot;.say; quot;Hello Worldquot;.print; # no newline quot;Hello Worldnquot;.print; qq/Hello Worldn/.print;
  22. 22. String concatenation ~ stitches strings together ( quot;Helloquot; ~ quot;Worldquot; ).say; HelloWorld ( quot;Helloquot; ~ quot; quot; ~ quot;Worldquot; ).say; Hello World
  23. 23. String replication x repeats and joins string ( quot;Hiquot; x 3 ).say; HiHiHi ( quot;Hiquot; x 2.5 ).say; floor - HiHi ( quot;Hiquot; x -1 ).say; error!
  24. 24. Booleans True or False, Yes or No, On or Off, 1 or nothing Often the result of a comparison
  25. 25. Numeric comparisons 5 < 6 True 5 > 6 False 5 == 6 False 5 <= 6 True 5 >= 6 False 5 != 6 True
  26. 26. String comparisons 'fred' lt 'barney' False 'fred' gt 'barney' True 'fred' eq 'barney' False 'fred' le 'barney' False 'fred' ge 'barney' True 'fred' ne 'barney' True
  27. 27. Scalar variables Stores a single value Name starts with a letter or underscore, followed by letters, underscores, or digits Has a special symbol (sigil) prepended, $ Starts off undefined (absence of value) We have to assign it a value Declare with my on first use
  28. 28. Scalar Assignment my $num = 5; quot;The number is $numquot;.say; my $str = quot;Pugsquot;; quot;Just another $str hacker, quot;.say;
  29. 29. Scalar value type The ref method gives the type of scalar my $s1 = 5 < 6; my $s2 = quot;Perlquot;; my $s3 = 6 - 5; my $s4 = 3.14; $s1.WHAT; Bool $s2.WHAT; Str $s3.WHAT; Int $s4.WHAT; Rat
  30. 30. Standard input quot;Enter a name> quot;.print; my $input = (=$*IN).chomp; quot;Enter another name> quot;.print; $input = (=<>).chomp;
  31. 31. Control Structures
  32. 32. if-elsif-else if 5 < 6 { quot;5 less than 6quot;.say } if 5 > 6 { quot;5 more than 6quot;.say } else { quot;5 not more than 6quot;.say } if 5 < 4 { quot;5 less than 4quot;.say } elsif 5 > 4 { quot;5 more than 4quot;.say } else { quot;5 not more than 4quot;.say }
  33. 33. Complex comparisons if( 5 < $x < 10 ) { quot;$x is between 5 and 10quot;.say } else { quot;$x is not between 5 and 10quot;.say }
  34. 34. Junctions my $num = 5; if( $num == any( <5 6 7> ) ) { quot;$num is in the setquot;.say } else { quot;$num is not in the setquot;.say }
  35. 35. Expression modifiers Apply a condition to a single expression quot;5 is greaterquot;.say if 5 > 6; quot;5 is lessquot;.say if 5 < 6;
  36. 36. loop loop ( init; test; increment ){ } loop ( $i = 1; $i < 10; $i++ ) { quot;I can count to $iquot;.say; } I can count to 1 I can count to 2 I can count to 3 I can count to 4 ...
  37. 37. next skips the rest of the block goes to next iteration loop ( $i = 1; $i < 10; $i++ ) { next if $i % 2; quot;I can count to $iquot;.say; } I can count to 2 I can count to 4 I can count to 6 I can count to 8
  38. 38. last skips the rest of the iterations continues after the loop loop ( $i = 1; $i < 10; $i++ ) { last if $i == 5; quot;I can count to $iquot;.say; } I can count to 2 I can count to 4 I can count to 6 I can count to 8
  39. 39. redo starts the current iteration again uses the same element (if any) loop { quot;Do you like pugs?> quot;.print; my $answer = (=$*IN).chomp; redo if $answer ne 'yes'; last; }
  40. 40. Number guesser quot;Guess secret number from 1 to 10quot;.say; my $secret = rand(10+1).int; loop { quot;Enter your guess> quot;.print; my $guess = (=$*IN).chomp; if $guess < $secret { quot;Too low!quot;.say; redo } elsif $guess > $secret { quot;Too high!quot;.say; redo } else { quot;That's it!quot;.say; last } }
  41. 41. Lists & Arrays
  42. 42. Literal Lists ( 1, 2, 3, 4 ) <a b c d> my $x = 'baz' <<foo bar $x>> «foo bar $x» ( 1 .. 3 ) ( 'a' .. 'z' )
  43. 43. List replication 'f' xx 4 <f f f f> <g> xx 6 <g g g g g g> < a b c > xx 2 < a b c a b c >
  44. 44. Joining elements <1 2 3 4>.join(' ') 1 2 3 4 <1 3 5 7>.join(':') 1:3:5:7
  45. 45. Ranges ( 4 .. 7 ) < 4 5 6 7 > ( 'a' .. 'e' ) < a b c d e > reverse 1 .. 3 < 3 2 1 > ( 1 .. 3 ).reverse < 3 2 1 >
  46. 46. Arrays Array variables store multiple scalars Indexes list with integers, starting at 0 Same variable naming rules as a scalar Special character is @ (think @rray) Name comes from a separate namespace Nothing to do with scalar of same name
  47. 47. Array assignment my @a = < a b c >; my @a = << a b $c >> my @a = 1 .. 6;
  48. 48. Bounds my @r = 37..42; say quot;Minimum is quot; ~ @r.min; say quot;Maximum is quot; ~ @r.max; my @a = < 3 5 9 2 5 0 1 8 4 >; say quot;Minimum is quot; ~ @a.min; say quot;Maximum is quot; ~ @a.max;
  49. 49. Array elements my @a = <a b c d e f g>; my $first = @a[0]; a my $last = @a[-1]; g my $count = @a.elems; 7 my @slice = @a[0,-1]; < a g >
  50. 50. Unique elements my @a = <a b c a b d b d>; my @b = @a.uniq; < a b c d >
  51. 51. Hyperoperators Apply operator pair wise my @nums = 1 .. 10; my @alphas = 'a' .. 'j'; my @stitch = @nums >>~<< @alphas; < 1a 2b 3c 4d 5e 6f 7g 8h 9i 10j > my @square = @nums >>*<< @nums; < 1 4 9 16 25 36 49 64 81 100 >
  52. 52. for for 1 .. 5 -> $elem { quot;I saw $elemquot;.say; } I saw 1 I saw 2 I saw 3 I saw 4 I saw 5
  53. 53. for for @ARGS -> $arg { quot;I saw $arg on the command linequot;.say; } I saw fred on the command line I saw barney on the command line I saw betty on the command line
  54. 54. Hashes
  55. 55. Hash variables Hash variables stores unordered pairs Index is the “key”, a unique string Makes a map from one thing to another Same naming rules as scalar and array Special character is % (think %hash) Name comes from a separate namespace Nothing to do with scalar, array of same name
  56. 56. Hash elements my %h = <a 5 b 7 c 3>; my $a_value = %h{'a'}; 5 my $b_value = %h<b>; 7 my $count = %h.elems; 3 my @values = %h{ <b c> }; < 7 3 > my @values = %h<b c>; < 7 3 >
  57. 57. my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', ); %hash.say; barney rubblefred flintstone %hash.join(quot;nquot;).say; barney rubble fred flintstone
  58. 58. Hash keys my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', ); for %hash.keys -> $key { quot;$key: %hash{$key}quot;.say; } barney: rubble fred: flintstone
  59. 59. Hash values my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', ); for %hash.values -> $value { quot;One value is $valuequot;.say; } One value is rubble One value is flintstone
  60. 60. By pairs my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', ); for %hash.kv -> $key, $value { quot;$key ---> $valuequot;.say; } barney ---> rubble fred ---> flintstone
  61. 61. Counting words my %words; for =<> -> $line { for $line.chomp.split -> $word { %words{$word}++; } } for %words.kv -> $k, $v { quot;$k: $vquot;.say }
  62. 62. exists True if the key is in the hash Does not create the key my @chars = <fred wilma barney betty>; my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', ); for @chars -> $char { quot;$char existsquot;.say if %hash.exists($char); }
  63. 63. delete Removes pair from hash my %hash = ( 'fred' => 'flintstone', 'barney' => 'rubble', 'dino' => undef, ); %hash.delete('dino'); %hash.join(quot;nquot;).say; barney rubble fred flintstone
  64. 64. Input Output
  65. 65. Standard input quot;Enter a name> quot;.print; my $input = (=$*IN).chomp; quot;Enter another name> quot;.print; $input = (=<>).chomp;
  66. 66. File input operator The =<> reads from files from the command line arguments for =<> -> $line { quot;Got $linequot;.print; }
  67. 67. Opening files to read my $fh = open( $file, :r ); for =$fh -> $line { quot;Got $linequot;.print; }
  68. 68. Die-ing my $file = quot;not_therequot;; my $fh = open( quot;not_therequot;, :r ) err die quot;Couldn’t open $file: $!quot;; for =$fh -> $line { quot;Got $linequot;.print; }
  69. 69. try Catches exceptions try { die quot;I'm dyingquot; if time.int % 2; quot;I made itquot;.say; }; quot;Error was $!quot;.say if $!;
  70. 70. Standard filehandles Default filehandles $*OUT and $*ERR $*ERR.say( quot;This goes to stderrquot; ); $*OUT.say( quot;This goes to stdoutquot; );
  71. 71. Writing to files my $file = quot;not_therequot;; my $fh = open( quot;not_therequot;, :w ) err die quot;Couldn’t open $file: $!quot;; print $fh: @stuff; # $fh.print( @stuff );
  72. 72. try Catches exceptions try { die quot;I'm dyingquot; if time.int % 2; quot;I made itquot;.say; }; quot;Error was $!quot;.say if $!;
  73. 73. Files and Directories
  74. 74. File tests my $file = quot;file_tests.p6quot;; quot;Found filequot;.say if $file ~~ :e; quot;Readable filequot;.say if $file ~~ :r; my $file_size = $file ~~ :s; # $file_size = stat($file).size quot;File size is $file_sizequot;.say;
  75. 75. Other topics
  76. 76. given is like C’s switch (but better) variable value types complex data structures regular expressions - PCRE and new stuff sorting, string manipulation etc. subroutines have better calling conventions
  77. 77. Summary Perl 6 is a new language It borrows from Perl (and ancestors) It’s not done yet, but it’s almost usable

×