root/docs/Perl6/Overview.pod

Revision 19635, 17.5 kB (checked in by tjp, 9 months ago)

Fixed typos in docs/Perl6/Overview.pod

  • Property svn:mime-type set to text/plain; charset=UTF-8
  • Property svn:eol-style set to native
Line 
1=begin maintainer_notes
2
3For now I'm basing this on the perlintro manpage.  I expect that a
4somewhat different structure will emerge over time, but it seems like as
5good a place to start as any.  -- Skud
6
7=end maintainer_notes
8
9
10=head1 NAME
11
12Perl6::Overview -- a brief introduction and overview of Perl 6
13
14=head1 DESCRIPTION
15
16This introduction is aimed at the beginning Perl 6 programmer.  For the
17moment, it is assumed that such programmers are coming from a background
18of Perl 5.  However, this document tries to be simple and general enough
19for anyone with some programming experience to pick up Perl 6.  Those
20who want more information about the changes from Perl 5 should look
21elsewhere.
22
23=head2 What is Perl 6?
24
25Perl 6, like its predecessors, is a multi-purpose dynamic language
26combining ease of use and powerful programming features.
27
28=head2 Running a Perl 6 program
29
30You will need to install Pugs, which can be found at
31L<http://pugscode.org/>.
32
33Having done so, you can run your Perl 6 program from the command line as
34follows:
35
36    pugs myprogram.pl
37
38To run one-liners from the command-line, use the -e flag:
39
40    pugs -e 'say "Hello, world!"'
41
42You can also start up pugs without any arguments, then type Perl 6 commands at
43its command line.  To exit, type C<ctrl-D> or C<:q>.
44
45=head2 Basic syntax overview
46
47A Perl 6 program consists of one or more statements.  These statements are
48simply written in a plain text file, one after another.  There is no need to
49have a C<main()> function or anything of that kind.
50
51Perl 6 statements end in a semi-colon:
52
53   say "Hello, world";
54
55Comments start with a hash symbol and run to the end of the line
56
57   # This is a comment
58
59Whitespace is irrelevant:
60
61   say
62       "Hello, world"
63       ;
64
65... except inside quoted strings:
66
67   # this would print with a linebreak in the middle
68   say "Hello
69   world";
70
71Double quotes or single quotes may be used around literal strings:
72
73   say "Hello, world";
74   say 'Hello, world';
75
76However, only double quotes "interpolate" variables and special characters
77such as newlines (C<\n>):
78
79   my $name = 'Johnny';
80   print "Hello, $name\n";   # prints: Hello, Johnny  (followed by a newline)
81   print 'Hello, $name\n';   # prints: Hello, $name\n (no newline)
82
83Numbers don't need quotes around them:
84
85   say 42;
86
87Most of the time, you can use parentheses for functions' arguments or omit
88them according to your personal taste.
89
90   say("Hello, world");
91   say "Hello, world";
92
93=head2 Perl variable types
94
95Perl has three main variable types: scalars, arrays, and hashes.
96Variables are declared with C<my>.
97
98=over 4
99
100=item Scalars
101
102A scalar represents a single value:
103
104    my $animal = "camel";
105    my $answer = 42;
106
107Scalar variables start with dollar signs. Scalar values can be strings,
108integers or floating point numbers, and Perl will automatically convert
109between them as required.  There is no need to pre-declare your variable
110types (though you can if you want -- see L<XXX>).
111
112Scalar values can be used in various ways:
113
114    say $animal;
115    say "The animal is $animal";
116    say "The square of $answer is ", $answer * $answer;
117
118There is a "magic" scalar with the name C<$_>, and it is referred to as
119the "topic".  It's used as the default argument to a number of functions
120in Perl, and it's set implicitly by certain constructs (so-called
121"topicalizing" constructs).
122
123    say;          # prints contents of $_ by default
124
125=item Arrays
126
127Array variables start with an at sign, and they represent lists of
128values:
129
130    my @animals = ("camel", "llama", "owl");
131    my @numbers = (23, 42, 69);
132    my @mixed   = ("camel", 42, 1.23);
133
134Arrays are zero-indexed.  Here's how you get at elements in an array:
135
136    say @animals[0];              # prints "camel"
137    say @animals[1];              # prints "llama"
138
139The numeric index of the last element of an array can by found with
140C<@array.end>:
141
142    say @animals[@animals.end];   # prints "owl"
143
144However, negative indices count backwards from the end of the list, so
145that could also have been written:
146
147    say @animals[-1];             # prints "owl"
148
149To find the number of elements in an array, use the C<elems> method:
150
151    say @mixed.elems;       # prints 3
152
153To get multiple values from an array:
154
155    @animals[0,1];                  # gives ("camel", "llama");
156    @animals[0..2];                 # gives ("camel", "llama", "owl");
157    @animals[1..@animals.end];      # gives all except the first element
158
159This is called an "array slice".
160
161You can do various useful things to lists:
162
163    my @sorted    = @animals.sort;
164    my @backwards = @numbers.reverse;
165
166There are a couple of special arrays too, such as C<@*ARGS> (the command
167line arguments to your script) and C<@_> (the arguments passed to a
168subroutine, if formal parameters are not declared).  These are documented
169in L<XXX>.
170
171=item Hashes
172
173Hash variables start with a percent sign, and represent sets of
174key/value pairs:
175
176    my %fruit_color = ("apple" => "red", "banana" => "yellow");
177
178You can use whitespace and the C<< => >> operator to lay them out more
179nicely:
180
181    my %fruit_color = (
182        apple  => "red",
183        banana => "yellow",
184    );
185
186To get at hash elements:
187
188    %fruit_color{"apple"};           # gives "red"
189
190You can get at lists of keys and values with C<keys()> and
191C<values()>.
192
193    my @fruits = %fruit_colors.keys;    # ("apple", "banana")
194    my @colors = %fruit_colors.values;  # ("red", "yellow")
195
196Hashes have no particular internal order, though you can sort the keys
197and loop through them.
198
199Just like special scalars and arrays, there are also special hashes.
200The most well known of these is C<%*ENV> which contains environment
201variables.  Read all about it (and other special variables) in
202L<XXX>.
203
204=back
205
206Scalars, arrays and hashes are documented more fully in L<perldata>.
207
208More complex data types can be constructed using references, which allow
209you to build lists and hashes within lists and hashes.
210
211A reference is a scalar value and can refer to any other Perl data
212type. So by storing a reference as the value of an array or hash
213element, you can easily create lists and hashes within lists and
214hashes. The following example shows a 2 level hash of hash
215structure using anonymous hash references.
216
217    my $variables = {
218        scalar  =>  {
219                     description => "single item",
220                     sigil => '$',
221                    },
222        array   =>  {
223                     description => "ordered list of items",
224                     sigil => '@',
225                    },
226        hash    =>  {
227                     description => "key/value pairs",
228                     sigil => '%',
229                    },
230    };
231
232    print "Scalars begin with a $variables{'scalar'}{'sigil'}\n";
233
234Exhaustive information on the topic of references can be found in
235L<perlreftut>, L<perllol>, L<perlref> and L<perldsc>.
236
237
238=head2 Variable scoping
239
240[XXX Please check and correct this... just my best attempt --aufrank]
241
242Variables in Perl 6 are put into one of several namespaces based on where
243and how they are declared.  The basic scopes available are global, package,
244and lexical.
245
246    use GLOBAL <$FOO>;  # globally-scoped $FOO
247    $*FOO;              # same as above
248    our $bar;           # package-scoped $bar
249    my $baz;            # lexically-scoped $baz
250
251Globally-scoped variables can be used anywhere within the current package,
252and can be used by any packages that use the current package.
253Package-scoped variables can be used anywhere in the current package, but
254cannot be accessed from outside the package.  Lexically-scoped variables can
255only be used within the scope of the nearest enclosing braces.
256
257    our $foo;
258    sub bar {
259        $foo++;         # OK, package-scoped $foo
260
261        my $baz;        # lexically-scoped $baz
262    }
263    $baz++;             # incorrect!  $baz is not in the package scope
264
265By default, variables declared in the root of the package are package
266scoped.  By default, variables declared within a block are lexically scoped.
267This includes variables declared in classes, objects, methods, subroutines,
268anonymous closures, rules, and conditional and looping constructs.
269
270There are also a number of specialized scopes available.  Many of these
271scopes are declared and accessed through the use of secondary sigils, or
272'twigils'.
273
274    $foo               # ordinary scoping
275    $.foo              # object attribute accessor
276    $^foo              # self-declared formal parameter
277    $*foo              # global variable
278    $+foo              # environmental variable
279    $?foo              # compiler hint variable
280    $=foo              # pod variable
281    $!foo              # explicitly private attribute (mapped to $foo though)
282
283Most variables with twigils are implicitly declared or assumed to be
284declared in some other scope, and don't need a "my" or "our".  Attribute
285variables are declared with "has", though, and environment variables are
286declared somewhere in the dynamic scope with the "env" declarator.
287
288By default, a subroutine or method hides variables declared within its
289lexical scope (with the exception of C<$_> ).  Variables declared within a
290subroutine or method cannot usually be accessed when the subroutine or method
291is called.  To change this, declare the variable with C<env>.
292
293    [XXX Probably should include an example declaring and accessing an ENV
294    variable]
295
296Variables within certain namespaces can be accessed through that namespace's
297symbol table.  Available symbol tables (or 'pseudo-packages') include:
298
299    MY           # lexical variables
300                 # declared with 'my'
301    OUR          # package variables
302                 # declared with 'our'
303    GLOBAL       # global scoped variables
304                 # declared with 'use GLOBAL' or $* twigil
305    ENV          # environmental variables
306                 # declared with 'env' or $+
307    OUTER        # the immediately surrounding 'MY' scope
308    CALLER       # the lexical scope of the caller
309    SUPER        # ???
310    COMPILING    # the compile-time scope of a variable, often used in macros
311                 # declared with $?
312
313=head2 Conditional and looping constructs
314
315Perl has most of the usual conditional and looping constructs.
316The are usually written as I<construct-name> I<condition> { ... }
317
318The conditions can be any Perl expression.  See the list of operators in
319the next section for information on comparison and boolean logic operators,
320which are commonly used in conditional statements.
321
322=over 4
323
324=item if
325
326    if condition {
327        ...
328    } elsif ( other condition ) {
329        ...
330    } else {
331        ...
332    }
333
334There's also a negated version of it:
335
336    unless condition {
337        ...
338    }
339
340This is provided as a more readable version of C<if not I<condition>>.
341
342C<...> is the "yada yada yada" operator.
343It is used as a place holder, which prints out a warning if executed.
344
345Note that the braces are required in Perl, even if you've only got one
346line in the block. However, there is a clever way of making your one-line
347conditional blocks more English like:
348
349    # the traditional way
350    if $zippy {
351        print "Yow!";
352    }
353
354    # the Perlish post-condition way
355    print "Yow!" if $zippy;
356    print "We have no bananas" unless $bananas;
357
358=item while
359
360    while condition {
361        ...
362    }
363
364There's also a negated version, for the same reason we have C<unless>:
365
366    until condition {
367        ...
368    }
369
370You can also use C<while> in a post-condition:
371
372    print "LA LA LA\n" while 1;          # loops forever
373
374=item loop
375
376The C<loop> functions exactly like the C's <for>
377It is rarely needed in Perl since Perl provides
378the more friendly list scanning C<for>.
379
380    loop (my $i=0; $i <= $max; $i++) {
381        ...
382    }
383
384Can be expressed like:
385
386    my $i=0;
387    while($i <= $max; ) {
388        ...;
389        $i++;
390    }
391
392If you want to create a neverending loop use C<loop> without
393any arguments
394
395    loop {
396        ...
397    }
398
399
400=item for
401
402    for @array {
403        print "This element is $_\n";
404    }
405
406    # you don't have to use the default $_ either...
407    for %hash.keys -> $key {
408        print "The value of $key is %hash{$key}\n";
409    }
410
411=back
412
413
414
415=head2 Built-in operators and functions
416
417Perl comes with a wide selection of builtin functions.  Some of the ones
418we've already seen include "print", "sort" and "reverse".  A list of them is
419given at the start of perlfunc and you can easily read about any given
420function by using "perldoc -f functionname".
421
422Perl operators are documented in full in perlop, but here are a few of the
423most common ones:
424
425Arithmetic
426       +   addition
427       -   subtraction
428       *   multiplication
429       /   division
430       **  exponentiation
431       %   modulo
432
433Numeric comparison
434       ==  equality
435       !=  inequality
436       <   less than
437       >   greater than
438       <=  less than or equal
439       =>  greater than or equal
440
441String comparison
442       eq  equality
443       ne  inequality
444       lt  less than
445       gt  greater than
446       le  less than or equal
447       ge  greater than or equal
448
449(Why do we have separate numeric and string comparisons?  Because we don't
450have special variable types, and Perl needs to know whether to sort
451numerically (where 99 is less than 100) or alphabetically (where 100 comes
452before 99).
453
454Smart comparison
455       ~~  smart match (see smartmatch)
456       !~~ negated smart match
457
458Boolean logic
459       &&  and
460       ||  or
461       !   not
462
463("and", "or" and "not" aren't just in the above table as descriptions of the
464operators -- they're also supported as operators in their own right.  They're
465more readable than the C-style operators, but have different precedence to
466"&&" and friends.  Check perlop for more detail.)
467
468Miscellaneous
469       =   assignment
470       ~   string concatenation
471       x   string multiplication
472       ..  range operator (creates a list of items)
473
474Many of the operators can be combined with an "=" as follows:
475      $a += 1;    # means $a = $a + 1;
476      $a -= 1;    # means $a = $a - 1;
477      $a ~= " ";  # means $a = $a ~ " "; 
478
479=head2 Files and I/O
480
481=head2 Rules
482
483Perl's rules are called regular expressions in other languges.
484Perl's regular expression support is both broad and deep, and is the
485subject of lengthy documentation in L<XXX>, and
486elsewhere.  However, in short:
487
488=over 4
489
490=item Simple matching
491
492    if /foo/       { ... }  # true if $_ contains "foo"
493    if $a ~~ /foo/ { ... }  # true if $a contains "foo"
494
495The C<//> matching operator is documented in L<XXX>.  It operates on
496C<$_> by default, or can be bound to another variable using the C<~~>
497smart match operator (also documented in L<XXX>).
498
499=item Simple substitution
500
501    s/foo/bar/;               # replaces foo with bar in $_
502    $a .= s/foo/bar/;         # replaces foo with bar in $a
503    $a .= s/foo/bar/g;        # replaces ALL INSTANCES of foo with bar in $a
504
505The C<s///> substitution operator is documented in L<XXX>.
506
507=item More complex regular expressions
508
509You don't just have to match on fixed strings.  In fact, you can match
510on just about anything you could dream of by using more complex regular
511expressions.  These are documented at great length in L<XXX>, but for
512the meantime, here's a quick cheat sheet:
513
514    .                   a single character
515    \N                  non-newline character
516    \s                  a whitespace character (space, tab, newline)
517    \S                  non-whitespace character
518    \d                  a digit (0-9)
519    \D                  a non-digit
520    \w                  a word character (a-z, A-Z, 0-9, _)
521    \W                  a non-word character
522    <[aeiou]>           matches a single character in the given set
523    <-[aeiou]>          matches a single character outside the given set
524    [foo|bar|baz]       matches any of the alternatives specified
525    (foo|bar|baz)       matches and captures any of the alternatives specified
526    <foo>               matches the rule foo
527    ^                   start of string
528    $                   end of string
529
530Quantifiers can be used to specify how many of the previous thing you
531want to match on, where "thing" means either a literal character, one
532of the metacharacters listed above, or a group of characters or
533metacharacters in parentheses.
534
535    *                   zero or more of the previous thing
536    +                   one or more of the previous thing
537    ?                   zero or one of the previous thing
538    **{3}               matches exactly 3 of the previous thing
539    **{3 .. 6}          matches between 3 and 6 of the previous thing
540
541Some brief examples:
542
543    /^\d+/              string starts with one or more digits
544    /^$/                nothing in the string (start and end are adjacent)
545    /[\d\s]{3}/         string contains three digits, each followed by a
546                        whitespace character (eg "3 4 5 ")
547    /[a.]+/             matches a string in which every odd-numbered letter
548                        is a (eg "abacadaf")
549
550    # This loop reads from STDIN, and prints non-blank lines:
551    for (=<>) {
552        next if /^$/;
553        print;
554    }
555
556=item Parentheses for capturing
557
558Additionaly to grouping, parentheses serve a second purpose.  They can be
559used to capture the results of parts of the regexp match for later use.
560The results end up in C<$0>, C<$1> and so on.
561Note that those variables are numbered from 0 not 1;
562
563    # a cheap and nasty way to break an email address up into parts
564
565    if ($email ~~ /(<-[@]>+)@(.+)/) {
566        print "Username is $0\n";
567        print "Hostname is $1\n";
568    }
569
570=item Other regexp features
571
572Perl rules also support named rules, grammars, backreferences, lookaheads, and
573all kinds of other complex details.  Read all about them in L<XXX>.
574
575=back
576
577=head2 Writing subroutines
578
579=head2 Object oriented Perl 6
580
581=head2 Using third-party modules
582
583=head1 AUTHOR
584
585Kirrily "Skud" Robert <skud@cpan.org>
586Shmarya <shmarya.rubenstein@gmail.com>
587Pawel Murias <13pawel@gazeta.pl>
Note: See TracBrowser for help on using the browser.