Cari di Perl 
    Perl User Tutorial
Daftar Isi
(Sebelumnya) The Perl 5 language interpreterHow to execute the Perl interpreter (Berikutnya)
Overview

A brief introduction and overview of Perl

Daftar Isi

NAME

perlintro -- a brief introduction and overview of Perl

DESCRIPTION

This document is intended to give you a quick overview of the Perlprogramming language, along with pointers to further documentation. Itis intended as a "bootstrap" guide for those who are new to thelanguage, and provides just enough information for you to be able toread other peoples' Perl and understand roughly what it's doing, orwrite your own simple scripts.

This introductory document does not aim to be complete. It does noteven aim to be entirely accurate. In some cases perfection has beensacrificed in the goal of getting the general idea across. You arestrongly advised to follow this introduction with more informationfrom the full Perl manual, the table of contents to which can be foundin perltoc.

Throughout this document you'll see references to other parts of thePerl documentation. You can read that documentation using the perldoccommand or whatever method you're using to read this document.

Throughout Perl's documentation, you'll find numerous examples intendedto help explain the discussed features. Please keep in mind that manyof them are code fragments rather than complete programs.

These examples often reflect the style and preference of the author ofthat piece of the documentation, and may be briefer than a correspondingline of code in a real program. Except where otherwise noted, youshould assume that use strict and use warnings statementsappear earlier in the "program", and that any variables used havealready been declared, even if those declarations have been omittedto make the example easier to read.

Do note that the examples have been written by many different authors overa period of several decades. Styles and techniques will therefore differ,although some effort has been made to not vary styles too widely in thesame sections. Do not consider one style to be better than others - "There'sMore Than One Way To Do It" is one of Perl's mottos. After all, in yourjourney as a programmer, you are likely to encounter different styles.

What is Perl?

Perl is a general-purpose programming language originally developed fortext manipulation and now used for a wide range of tasks includingsystem administration, web development, network programming, GUIdevelopment, and more.

The language is intended to be practical (easy to use, efficient,complete) rather than beautiful (tiny, elegant, minimal). Its majorfeatures are that it's easy to use, supports both procedural andobject-oriented (OO) programming, has powerful built-in support for textprocessing, and has one of the world's most impressive collections ofthird-party modules.

Different definitions of Perl are given in perl, perlfaq1 andno doubt other places. From this we can determine that Perl is differentthings to different people, but that lots of people think it's at leastworth writing about.

Running Perl programs

To run a Perl program from the Unix command line:

  1. perl progname.pl

Alternatively, put this as the first line of your script:

  1. #!/usr/bin/env perl

... and run the script as /path/to/script.pl. Of course, it'll needto be executable first, so chmod 755 script.pl (under Unix).

(This start line assumes you have the env program. You can also putdirectly the path to your perl executable, like in #!/usr/bin/perl).

For more information, including instructions for other platforms such asWindows and Mac OS, read perlrun.

Safety net

Perl by default is very forgiving. In order to make it more robustit is recommended to start every program with the following lines:

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;

The two additional lines request from perl to catch various commonproblems in your code. They check different things so you need both. Apotential problem caught by use strict; will cause your code to stopimmediately when it is encountered, while use warnings; will merelygive a warning (like the command-line switch -w) and let your code run.To read more about them check their respective manual pages at strictand warnings.

Basic syntax overview

A Perl script or program consists of one or more statements. Thesestatements are simply written in the script in a straightforwardfashion. There is no need to have a main() function or anything ofthat kind.

Perl statements end in a semi-colon:

  1. print "Hello, world";

Comments start with a hash symbol and run to the end of the line

  1. # This is a comment

Whitespace is irrelevant:

  1. print
  2. "Hello, world"
  3. ;

... except inside quoted strings:

  1. # this would print with a linebreak in the middle
  2. print "Hello
  3. world";

Double quotes or single quotes may be used around literal strings:

  1. print "Hello, world";
  2. print 'Hello, world';

However, only double quotes "interpolate" variables and specialcharacters such as newlines (\n):

  1. print "Hello, $name\n"; # works fine
  2. print 'Hello, $name\n'; # prints $name\n literally

Numbers don't need quotes around them:

  1. print 42;

You can use parentheses for functions' arguments or omit themaccording to your personal taste. They are only requiredoccasionally to clarify issues of precedence.

  1. print("Hello, world\n");
  2. print "Hello, world\n";

More detailed information about Perl syntax can be found in perlsyn.

Perl variable types

Perl has three main variable types: scalars, arrays, and hashes.

  • Scalars

    A scalar represents a single value:

    1. my $animal = "camel";
    2. my $answer = 42;

    Scalar values can be strings, integers or floating point numbers, and Perlwill automatically convert between them as required. There is no needto pre-declare your variable types, but you have to declare them usingthe my keyword the first time you use them. (This is one of therequirements of use strict;.)

    Scalar values can be used in various ways:

    1. print $animal;
    2. print "The animal is $animal\n";
    3. print "The square of $answer is ", $answer * $answer, "\n";

    There are a number of "magic" scalars with names that look likepunctuation or line noise. These special variables are used for allkinds of purposes, and are documented in perlvar. The only one youneed to know about for now is $_ which is the "default variable".It's used as the default argument to a number of functions in Perl, andit's set implicitly by certain looping constructs.

    1. print; # prints contents of $_ by default
  • Arrays

    An array represents a list of values:

    1. my @animals = ("camel", "llama", "owl");
    2. my @numbers = (23, 42, 69);
    3. my @mixed = ("camel", 42, 1.23);

    Arrays are zero-indexed. Here's how you get at elements in an array:

    1. print $animals[0]; # prints "camel"
    2. print $animals[1]; # prints "llama"

    The special variable $#array tells you the index of the last elementof an array:

    1. print $mixed[$#mixed]; # last element, prints 1.23

    You might be tempted to use $#array + 1 to tell you how many items thereare in an array. Don't bother. As it happens, using @array where Perlexpects to find a scalar value ("in scalar context") will give you the numberof elements in the array:

    1. if (@animals < 5) { ... }

    The elements we're getting from the array start with a $ becausewe're getting just a single value out of the array; you ask for a scalar,you get a scalar.

    To get multiple values from an array:

    1. @animals[0,1]; # gives ("camel", "llama");
    2. @animals[0..2]; # gives ("camel", "llama", "owl");
    3. @animals[1..$#animals]; # gives all except the first element

    This is called an "array slice".

    You can do various useful things to lists:

    1. my @sorted = sort @animals;
    2. my @backwards = reverse @numbers;

    There are a couple of special arrays too, such as @ARGV (the commandline arguments to your script) and @_ (the arguments passed to asubroutine). These are documented in perlvar.

  • Hashes

    A hash represents a set of key/value pairs:

    1. my %fruit_color = ("apple", "red", "banana", "yellow");

    You can use whitespace and the => operator to lay them out morenicely:

    1. my %fruit_color = (
    2. apple => "red",
    3. banana => "yellow",
    4. );

    To get at hash elements:

    1. $fruit_color{"apple"}; # gives "red"

    You can get at lists of keys and values with keys() andvalues().

    1. my @fruits = keys %fruit_colors;
    2. my @colors = values %fruit_colors;

    Hashes have no particular internal order, though you can sort the keysand loop through them.

    Just like special scalars and arrays, there are also special hashes.The most well known of these is %ENV which contains environmentvariables. Read all about it (and other special variables) inperlvar.

Scalars, arrays and hashes are documented more fully in perldata.

More complex data types can be constructed using references, which allowyou to build lists and hashes within lists and hashes.

A reference is a scalar value and can refer to any other Perl datatype. So by storing a reference as the value of an array or hashelement, you can easily create lists and hashes within lists andhashes. The following example shows a 2 level hash of hashstructure using anonymous hash references.

  1. my $variables = {
  2. scalar => {
  3. description => "single item",
  4. sigil => '$',
  5. },
  6. array => {
  7. description => "ordered list of items",
  8. sigil => '@',
  9. },
  10. hash => {
  11. description => "key/value pairs",
  12. sigil => '%',
  13. },
  14. };
  15. print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";

Exhaustive information on the topic of references can be found inperlreftut, perllol, perlref and perldsc.

Variable scoping

Throughout the previous section all the examples have used the syntax:

  1. my $var = "value";

The my is actually not required; you could just use:

  1. $var = "value";

However, the above usage will create global variables throughout yourprogram, which is bad programming practice. my creates lexicallyscoped variables instead. The variables are scoped to the block(i.e. a bunch of statements surrounded by curly-braces) in which theyare defined.

  1. my $x = "foo";
  2. my $some_condition = 1;
  3. if ($some_condition) {
  4. my $y = "bar";
  5. print $x; # prints "foo"
  6. print $y; # prints "bar"
  7. }
  8. print $x; # prints "foo"
  9. print $y; # prints nothing; $y has fallen out of scope

Using my in combination with a use strict; at the top ofyour Perl scripts means that the interpreter will pick up certain commonprogramming errors. For instance, in the example above, the finalprint $y would cause a compile-time error and prevent you fromrunning the program. Using strict is highly recommended.

Conditional and looping constructs

Perl has most of the usual conditional and looping constructs. As of Perl5.10, it even has a case/switch statement (spelled given/when). SeeSwitch Statements in perlsyn for more details.

The conditions can be any Perl expression. See the list of operators inthe next section for information on comparison and boolean logic operators,which are commonly used in conditional statements.

  • if
    1. if ( condition ) {
    2. ...
    3. } elsif ( other condition ) {
    4. ...
    5. } else {
    6. ...
    7. }

    There's also a negated version of it:

    1. unless ( condition ) {
    2. ...
    3. }

    This is provided as a more readable version of if (!condition).

    Note that the braces are required in Perl, even if you've only got oneline in the block. However, there is a clever way of making your one-lineconditional blocks more English like:

    1. # the traditional way
    2. if ($zippy) {
    3. print "Yow!";
    4. }
    5. # the Perlish post-condition way
    6. print "Yow!" if $zippy;
    7. print "We have no bananas" unless $bananas;
  • while
    1. while ( condition ) {
    2. ...
    3. }

    There's also a negated version, for the same reason we have unless:

    1. until ( condition ) {
    2. ...
    3. }

    You can also use while in a post-condition:

    1. print "LA LA LA\n" while 1; # loops forever
  • for

    Exactly like C:

    1. for ($i = 0; $i <= $max; $i++) {
    2. ...
    3. }

    The C style for loop is rarely needed in Perl since Perl providesthe more friendly list scanning foreach loop.

  • foreach
    1. foreach (@array) {
    2. print "This element is $_\n";
    3. }
    4. print $list[$_] foreach 0 .. $max;
    5. # you don't have to use the default $_ either...
    6. foreach my $key (keys %hash) {
    7. print "The value of $key is $hash{$key}\n";
    8. }

    The foreach keyword is actually a synonym for the forkeyword. See Foreach Loops in perlsyn.

For more detail on looping constructs (and some that weren't mentioned inthis overview) see perlsyn.

Builtin operators and functions

Perl comes with a wide selection of builtin functions. Some of the oneswe've already seen include print, sort and reverse. A list ofthem is given at the start of perlfunc and you can easily readabout any given function by using perldoc -f functionname.

Perl operators are documented in full in perlop, but here are a fewof the most common ones:

  • Arithmetic
    1. + addition
    2. - subtraction
    3. * multiplication
    4. / division
  • Numeric comparison
    1. == equality
    2. != inequality
    3. < less than
    4. > greater than
    5. <= less than or equal
    6. >= greater than or equal
  • String comparison
    1. eq equality
    2. ne inequality
    3. lt less than
    4. gt greater than
    5. le less than or equal
    6. ge greater than or equal

    (Why do we have separate numeric and string comparisons? Because we don'thave special variable types, and Perl needs to know whether to sortnumerically (where 99 is less than 100) or alphabetically (where 100 comesbefore 99).

  • Boolean logic
    1. && and
    2. || or
    3. ! not

    (and, or and not aren't just in the above table as descriptionsof the operators. They're also supported as operators in their ownright. They're more readable than the C-style operators, but havedifferent precedence to && and friends. Check perlop for moredetail.)

  • Miscellaneous
    1. = assignment
    2. . string concatenation
    3. x string multiplication
    4. .. range operator (creates a list of numbers)

Many operators can be combined with a = as follows:

  1. $a += 1; # same as $a = $a + 1
  2. $a -= 1; # same as $a = $a - 1
  3. $a .= "\n"; # same as $a = $a . "\n"

Files and I/O

You can open a file for input or output using the open() function.It's documented in extravagant detail in perlfunc and perlopentut,but in short:

  1. open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
  2. open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
  3. open(my $log, ">>", "my.log") or die "Can't open my.log: $!";

You can read from an open filehandle using the <> operator. Inscalar context it reads a single line from the filehandle, and in listcontext it reads the whole file in, assigning each line to an element ofthe list:

  1. my $line = <$in>;
  2. my @lines = <$in>;

Reading in the whole file at one time is called slurping. It canbe useful but it may be a memory hog. Most text file processingcan be done a line at a time with Perl's looping constructs.

The <> operator is most often seen in a while loop:

  1. while (<$in>) { # assigns each line in turn to $_
  2. print "Just read in this line: $_";
  3. }

We've already seen how to print to standard output using print().However, print() can also take an optional first argument specifyingwhich filehandle to print to:

  1. print STDERR "This is your final warning.\n";
  2. print $out $record;
  3. print $log $logmessage;

When you're done with your filehandles, you should close() them(though to be honest, Perl will clean up after you if you forget):

  1. close $in or die "$in: $!";

Regular expressions

Perl's regular expression support is both broad and deep, and is thesubject of lengthy documentation in perlrequick, perlretut, andelsewhere. However, in short:

  • Simple matching
    1. if (/foo/) { ... } # true if $_ contains "foo"
    2. if ($a =~ /foo/) { ... } # true if $a contains "foo"

    The // matching operator is documented in perlop. It operates on$_ by default, or can be bound to another variable using the =~binding operator (also documented in perlop).

  • Simple substitution
    1. s/foo/bar/; # replaces foo with bar in $_
    2. $a =~ s/foo/bar/; # replaces foo with bar in $a
    3. $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a

    The s/// substitution operator is documented in perlop.

  • More complex regular expressions

    You don't just have to match on fixed strings. In fact, you can matchon just about anything you could dream of by using more complex regularexpressions. These are documented at great length in perlre, but forthe meantime, here's a quick cheat sheet:

    1. . a single character
    2. \s a whitespace character (space, tab, newline, ...)
    3. \S non-whitespace character
    4. \d a digit (0-9)
    5. \D a non-digit
    6. \w a word character (a-z, A-Z, 0-9, _)
    7. \W a non-word character
    8. [aeiou] matches a single character in the given set
    9. [^aeiou] matches a single character outside the given set
    10. (foo|bar|baz) matches any of the alternatives specified
    11. ^ start of string
    12. $ end of string

    Quantifiers can be used to specify how many of the previous thing youwant to match on, where "thing" means either a literal character, oneof the metacharacters listed above, or a group of characters ormetacharacters in parentheses.

    1. * zero or more of the previous thing
    2. + one or more of the previous thing
    3. ? zero or one of the previous thing
    4. {3} matches exactly 3 of the previous thing
    5. {3,6} matches between 3 and 6 of the previous thing
    6. {3,} matches 3 or more of the previous thing

    Some brief examples:

    1. /^\d+/ string starts with one or more digits
    2. /^$/ nothing in the string (start and end are adjacent)
    3. /(\d\s){3}/ a three digits, each followed by a whitespace
    4. character (eg "3 4 5 ")
    5. /(a.)+/ matches a string in which every odd-numbered letter
    6. is a (eg "abacadaf")
    7. # This loop reads from STDIN, and prints non-blank lines:
    8. while (<>) {
    9. next if /^$/;
    10. print;
    11. }
  • Parentheses for capturing

    As well as grouping, parentheses serve a second purpose. They can beused to capture the results of parts of the regexp match for later use.The results end up in $1, $2 and so on.

    1. # a cheap and nasty way to break an email address up into parts
    2. if ($email =~ /([^@]+)@(.+)/) {
    3. print "Username is $1\n";
    4. print "Hostname is $2\n";
    5. }
  • Other regexp features

    Perl regexps also support backreferences, lookaheads, and all kinds ofother complex details. Read all about them in perlrequick,perlretut, and perlre.

Writing subroutines

Writing subroutines is easy:

  1. sub logger {
  2. my $logmessage = shift;
  3. open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
  4. print $logfile $logmessage;
  5. }

Now we can use the subroutine just as any other built-in function:

  1. logger("We have a logger subroutine!");

What's that shift? Well, the arguments to a subroutine are availableto us as a special array called @_ (see perlvar for more on that).The default argument to the shift function just happens to be @_.So my $logmessage = shift; shifts the first item off the list ofarguments and assigns it to $logmessage.

We can manipulate @_ in other ways too:

  1. my ($logmessage, $priority) = @_; # common
  2. my $logmessage = $_[0]; # uncommon, and ugly

Subroutines can also return values:

  1. sub square {
  2. my $num = shift;
  3. my $result = $num * $num;
  4. return $result;
  5. }

Then use it like:

  1. $sq = square(8);

For more information on writing subroutines, see perlsub.

OO Perl

OO Perl is relatively simple and is implemented using references whichknow what sort of object they are based on Perl's concept of packages.However, OO Perl is largely beyond the scope of this document.Read perlootut and perlobj.

As a beginning Perl programmer, your most common use of OO Perl will bein using third-party modules, which are documented below.

Using Perl modules

Perl modules provide a range of features to help you avoid reinventingthe wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). Anumber of popular modules are included with the Perl distributionitself.

Categories of modules range from text manipulation to network protocolsto database integration to graphics. A categorized list of modules isalso available from CPAN.

To learn how to install modules you download from CPAN, readperlmodinstall.

To learn how to use a particular module, use perldoc Module::Name.Typically you will want to use Module::Name, which will then giveyou access to exported functions or an OO interface to the module.

perlfaq contains questions and answers related to many commontasks, and often provides suggestions for good CPAN modules to use.

perlmod describes Perl modules in general. perlmodlib lists themodules which came with your Perl installation.

If you feel the urge to write Perl modules, perlnewmod will give yougood advice.

AUTHOR

Kirrily "Skud" Robert <[email protected]>

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) The Perl 5 language interpreterHow to execute the Perl interpreter (Berikutnya)