Perl

http://www.activestate.com/activeperl/downloads

Articles

http://perldoc.perl.org/perlcheat.html
http://perlmonks.org/?node_id=216602 - another cheat sheet
http://perlmonks.org/?node_id=238031 - Cheat sheet for Perl 6
http://juerd.nl/site.plp/perlcheat - another

Cheat
Miscellaneous
Array
Hash
Time
Signal
Flow control
Working with files
Working with dbm
LWP / Making web requests
CGI
Working with databases (DBI, DBD, mysql)
Sending email
Working with email
Working with command-line options (GetOpt)
Regular expresion
More code samples
One liners
printf
format

Moose
Catalyst
Sigill / Data structure
OOP
Design Pattern
mod_perl
Templating systems
Mime::Parser
Testing
Debugging
Catch system error
Log::Log4perl
Module installation and miscellaneous commands

Socket Programming
Signal Handling
Gotchas
The Parrot Virtual Machine
Pugs

Mottos

perl-shorthand-instance-variables

What is Perl and why should we use Perl?

Officially, Perl stands for Practical Extraction and Report Language, except when it doesn't. Perl was originally a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It quickly became a good language for many system management tasks. Over the years, Perl has grown into a general-purpose programming language. It's widely used for everything from quick "one-liners" to full-scale application development.

The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). It combines (in the author's opinion, anyway) some of the best features of sed, awk, and sh, making it familiar and easy to use for Unix users to whip up quick solutions to annoying problems. Its general-purpose programming facilities support procedural, functional, and object-oriented programming paradigms, making Perl a comfortable language for the long haul on major projects, whatever your bent.

Perl's roots in text processing haven't been forgotten over the years. It still boasts some of the most powerful regular expressions to be found anywhere, and its support for Unicode text is world-class. It handles all kinds of structured text, too, through an extensive collection of extensions. Those libraries, collected in the CPAN, provide ready-made solutions to an astounding array of problems. When they haven't set the standard themselves, they steal from the best — just like Perl itself.

How can we get started with Perl?

If you are using Unix / Linux, chances are good that Perl is already installed. If not, you can use the appropriate package manager for your operating system to install Perl. If you use Windows, you can google Perl and download the one from Active State.

Just open up a text editor, and paste:

#!/usr/bin/perl
use strict;
no warnings qw(uninitialized);
use English '-no_match_vars';
sub printSomething {
    $message = shift;
    print $message;
}
printSomething("Hello world");

Save the file, and then run it:

./filename.pl
perl filename.pl

Read the OOP page and other links on this page for sample code.

How can we do a syntax check on our code?

perl -c filename.pl

How can we use gethostbyname to determine its IP address?

use Socket qw(inet_ntoa);
$name = 'www.example.com';
my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyname($name);
$ip = inet_ntoa($addrs[0]);

What is the purpose of the package statement?

The package statement define the name space for a Perl module.

Can we define multiple packages in a single file?

Yes.

package Sophie;
sub say_hello {
    print "Hi World!";
}

package Clara;
use Sophie;           # loads the package but does NOT import any methods
say_hello();          # blows up
Sophie->say_hello();  # correct usage
Sophie::say_hello();  # works, but not for inherited methods

Can a package be spread across multiple file?

Yes.

What happen when you use a module?

When you use a package such as Some::Package, Perl looks for a file Some/Package.pm in the current directory. If this file doesn't exist, it looks for it in the system's global directory (like c:/perl/lib) and in the global @INC array.

How can we cause Perl to look for module in our own user-defined location?

It is a good idea to save your application packages to a directory like lib and add that directory to the list of namespace roots using use lib 'my/root/path':

use lib 'lib';      # Add the sub-directory 'lib' to the namespace root @INC
use Some::Package;  # Walks through @INC to find the package file

How can a module export its subroutines and variables into the global namespace?

This is not recommended, unless you have a really good reason. In order to export symbols, inherit from the Exporter class and fill the @EXPORT array with the symbols you'd like to export:

package Util;
use base 'Exporter';
our @EXPORT = ('foo', 'bar');

sub foo {
    print "foo!";
}
sub bar {
    print "bar!";
}

package Amy;
use Util;  # imports symbols in @EXPORT
foo();     # works fine
bar();     # works fine

The above code exports the foo and bar function by default. It might be a good idea to leave it up to the requiring package to decide which symbols get exported into its namespace. In that case you simply use the @EXPORT_OK array instead or @EXPORT:

package Util;
use base 'Exporter';
our @EXPORT_OK = ('foo', 'bar');

sub foo {
    print "foo!";
}
sub bar {
    print "bar!";
}

package Amy;
use Util 'foo';  # only import foo()
foo();           # works fine
bar();           # blows up

How can we import symbols from another module?

package Student;
use Some::Package 'param1', 'param2';

Whenever you use a package, the static method import is called in that package with all parameters you might have given:

package Some::Package;
sub import {
    my($class, @params) = @_;
}

How can we determine the caller of a subroutine?

The caller() function lets you (among other things) find out what class was calling the current method:

package Some::Package;
sub import {
    my($class, @params) = @_;
    print "Look, " . caller() . " is trying to import me!";
}

How can we iterate over an array using the foreach construct?

foreach my $role ( qw( Flier Digger Feline ) ) {
}

How can we access environment variables?

$ENV{"PATH"};

How can we execute an external command?

system("command");

How can I make my perl program run faster?

  1. Benchmark and profile to make sure that you are optimizing the right part.
  2. Look for better algorithm instead of microtuning your code, and when all else fail, consider buying better/faster hardware.
  3. Autoload seldom-used Perl code. See AutoSplit and AutoLoader module.
  4. Locate bottlenecks and think about writing those parts in C or assembly. See Inline module.
  5. If your perl executable is currently linked to libc.so, you can often gain 10-25% performance benefit by rebuilding it to link to the static libc.a instead. This make a bigger executable but your perl program may thank you for it. If your server is only for serving mod_perl code, you may want to double check.
  6. Using substr() or vec() to simulate arrays can be highly beneficial.
  7. The standard Tie::SubstrHash module can also help for certain types of data structure.
  8. If you're working with specialist data structures (matrices, for instance) modules that implement these in C may use less memory than equivalent in Perl modules.
  9. Another thing to try is to learn whether your Perl was compiled with the system's malloc or with Perl's builtin malloc. Whichever one it is, try using the other one and see whether this make a difference. You can find out whether you are using perl's malloc by typeing "perl -V:usemymalloc"
  10. Don't read an entire file into memory if you can process it line by line.
  11. Avoid using map and grep on large list.
  12. Avoid unnecessary quotes and stringifications
  13. Avoid stringifying arrays: { local $, = ""; print @big_arrays; }
  14. Pass by reference. Pass arrays and hashes by reference, not by value. It avoids creating a copy of all the contents.
  15. Tie large variables to disk. For big data stores, ones that exceed available memory, consider using one of the DB modules to store it on disk instead of RAM. This will incur a penalty in access time, but that's probably better than causing your hard disk to thrash due to massive swapping.
  16. Don't use English.pm because it export a lot of variables (need verification)
print("Hello world!\n");
$name = <STDIN>
chomp($name);

eq, ne
@array = ("camel","llama","alpaca");
@array = qw(camel, llama, alpaca);
$array[i]
%hash = qw(fred camel barney llama betty alpaca wilma alpaca);
$hash{"key"};

($name =~ /^Randal/)
($name =~ /^Randal/i)    # ignore-case
($name =~ /^randal\b/i)    # word boundary special marker
$name =~ s/\w.*//;        # \w stand for non-word character (something beside letters, digits, or underscore)
$name =~ tr/A-Z/a-z/;

format STDOUT =
@<<<<<<<<< @<<<<<<<<< @<<<<<<<<<
$filename, $name, $word
.

format STDOUT_TOP =
Page @<<
$%
Filename    Name    Word
====    ===    ====
.

dbmopen(%last_good, "lastdb", 0666);
$last_good{$name} = time;
dbmclose(%last_good);

keys(%last_good);     // returns a list of keys
sort(list)            // sort a list alphabetically
foreach $name (sort keys(%last_good)) { .. }

($e, @fred) = @fred;    // remove the first element of @fred to $e
$a = @fred;    // $a is the length of @fred
($a) = @fred;    // $a is the first element of @fred
@fred[0,1] = @fred[1,0]
$#fred    // index of the last value (element) of fred
push(@mylist, $newvalue);
$oldvalue = pop(@mylist);
unshift(@fred,$a);
$x = shift(@fred);
reverse(@a);
sort(@str);
chomp(@list);

\n    newline
\r    carriage return
\t    tab
\f    formfeed
\b    backspace
\a    bell
\e    escape
\007    bell
\x7f    delete
\cz    control character
\\    backslash
\"    double quote
\l    (lower-case letter l) lower-case the next character
\L    lower-case until \E
\u    upper-case the next character
\U    upper-case until \E
\Q    backslash all non-alphanumeric character until
\E    terminate \L, \U, and \Q

chr($a)    // returns the corresponding character (in this case, $a is a number)
ord($a)    // returns the corresponding number (in this case, $a is a character)
lc, lcfirst
uc, ucfirst
length
index
rindex
substr

last    // break
next    // continue
redo    // goto label

$_    // default input separator
$\    // output record separator
$/    // input record separator
$"    // output list separator
$,    // output field separator
$.    // current input line number
(x .. y)    // range of input line

keys
values
each    // return the next key value pair
delete
exists

split(/pattern/, string, limit)        // In a list context, split returns a list of substring found.
                        // In a scalar context, returns the count of substring found.

join("separator string", list)
map(expression, list)    // returns a list of result
grep(expression,list)    // returns the number of pattern found (in scalar)
                // returns a list of pattern found in list context

printf specifier format
pack
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License