Perl Programming

From Omnia
Revision as of 21:48, 14 May 2019 by Kenneth (talk | contribs) (Created page with "== Tutorials == === Local === Perl - Kenneth Learning Perl Perl 4 Tutorial UTOSC 2008 - Perl Fundamentals === External === [http://perldoc.perl.org/inde...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Tutorials

Local

Perl - Kenneth

Learning Perl

Perl 4 Tutorial

UTOSC 2008 - Perl Fundamentals

External

Tutorials - perldoc.perl.org

Perl Monks - Tutorials

Chan Bernard Ki Hong - Perl 5 Tutorial

Page Resource - Beginning Perl Tutorials

CGI Programming 101 - Learn CGI Today

Picking Up Perl, Edition 0.12, A Freely Redistributable Perl Tutorial Book

"This site was created as an early distribution center for Picking Up Perl. Picking Up Perl is a freely redistributable tutorial book on Perl."

Robert's Perl Tutorial

"A basic Perl course primarily for use on Win32 platforms. It assumes that the reader knows nothing of programming whatsoever, but needs a solid grounding for further work. After you finish this course you'll be ready to specialise in CGI, sysadmin or whatever you want to do with Perl. "

perl.com: Beginner's Introduction to Perl

"Welcome to Perl. Perl is the Swiss Army chainsaw of scripting languages: powerful and adaptable. It was first developed by Larry Wall, a linguist working as a systems administrator for NASA in the late 1980s, as a way to make report processing easier. Since then, it has moved into a large number of roles: automating system administration, acting as glue between different computer systems; and, of course, being one of the most popular languages for CGI programming on the Web."

perlsyn - perldoc.perl.org:

perlsyn - Perl syntax:
"A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines and other control structures allow you to jump around within the code."

Periodic Table of the Perl Operators

Periodic Table of the Per Operators (JPEG Image, 3477x2456 pixels)

The Periodic table of Perl operator (local copy)

Reference Article: The Periodic table of Perl operators - LWN.net:

The Periodic table of Perl operators
An updated version of the periodic table of the operators for Perl 6 has been posted. It is truly a work of art, to say the least; suitable for framing.

What does "Perl" stand for

"Perl is sometimes called the "Practical Extraction and Report Language," although it has also been caled a "Pathologically Eclectic Rubbish Lister," among other explanations. It's actually a backronym, not an acronym, since Larry Wall (Perl's creator) came up with the name first and the expansion later. That's why "Perl" isn't in all caps. There's no point in arguing which expansion is correct: Larry endorses both. (Source: Learning Perl book)

Perl Administration

Show Perl Version

$ perl -v
This is perl, v5.8.8 built for i386-linux-thread-multi

Perl One Liners

perl -e '...CODE...';

Install Modules

To install a CPAN module:

perl -MCPAN -e "install [MODULE]"

CPAN Shell:

perl -MCPAN -e 'shell'

perlmodinstall:

"If you are uncomfortable with having something take that much control over your software installation, or it otherwise doesn't work for you, the perlmodinstall documentation covers module installation for UNIX, Windows and Macintosh in more familiar terms. "

windows:

"If you're using ActivePerl on Windows, the PPM (Perl Package Manager) has much of the same functionality as CPAN.pm. "

Source:

Compiling Module

perl Makefile.pl
make
make test
make install

Source: How To Install Perl Modules Manually and Using CPAN command

CPAN

CPAN Shell

perl -MCPAN -e shell

Initially will run through configuration. If you wish to rerun configuration:

> o conf init

To install a module:

> install [MODULE]

To install from the command line:

cpan [MODULE]
perl -MCPAN -e "install [MODULE]"


See Also Perl - CPAN

perldoc

perldoc [MODULE]
perldoc -f [FUNCTION]

Obfuscated Perl

An obfuscated program is purposely written in an incomprehensible manner, so that it is very difficult to understand or reverse-engineer. Perl is one of the classic languages for obfuscated code, and in fact there is an obfuscated Perl contest. This little gem of a script is not only obfuscated, it's arguably a fine piece of ascii artwork. It's a perfectly legal Perl script, and produces even more pretty camel pictures when you run it. Have a look, if only for a laugh.

Perl Monks - Obfuscated code

unmaintainable code : Java Glossary

"unmaintainable code - This is my most popular essay. It is amazing how many people don’t realise it is tongue in cheek"
"To foil the maintenance programmer, you have to understand how he thinks. He has your giant program. He has no time to read it all, much less understand it. He wants to rapidly find the place to make his change, make it and get out and have no unexpected side effects from the change.
He views your code through a toilet paper tube. He can only see a tiny piece of your program at a time. You want to make sure he can never get at the big picture from doing that. You want to make it as hard as possible for him to find the code he is looking for. But even more important, you want to make it as awkward as possible for him to safely ignore anything.
Programmers are lulled into complacency by conventions. By every once in a while, by subtly violating convention, you force him to read every line of your code with a magnifying glass.
You might get the idea that every language feature makes code unmaintainable — not so, only if properly misused. "

Writing highly obfuscated code in Perl

  • Take advantage of Perl's end of line character ";". Use it to dirty up your code. For example, if you want to go for a certain shape you can use ";"'s to spruce it u
  • Always break up your equal signs.
  • Don't forget that, if you need better "shaping", always break up your strings with a new line character "\n";
  • Regular expressions make for messy code, and that is what we are going for. Use them in excess whenever possible.
  • Add comments. Sometimes adding odd comments here and there can help enhance the shaping of your code. An example of this is found in my work : "modern (perl) art" in the Obfuscated Code section of www.perlmonks.org. However,never comment in a way that would clarify your code.
  • Try to name your variables in a simplistic, yet inconherent way. "woodzy" has done a great job of this with his work called "Email sig. Old news. :/" on www.perlmonks.org.
  • Keep working. Practice enough and you WILL get good results. Someday you will even do lettering. You don't beleive that thats possible? Check out "Yet Another Perl Conference" by Erudil and you will see what I mean.
  • Keep your code as mathematical as possible. Never leave a simple expression alone, ie (4+4), but rather turn it into (((1*3)+1) + ((100*((1*2)+2)) /(10*10))). Doing this will make your code unreadable real soon.
  • Packing and unpacking will cause your code to be just a bit more unreadble. You will find many examples of this in www.perlmonks.org Obfuscated Code board.
  • Be sure to view some of the code found in Obfuscated Code section of www.perlmonks.org, its real helpfull on giving you some ideas on where to get started at making your code more un-readable. Please note that this is by no means a complete tutorial. I really hope that some other "perl obfuscator" will jump in and write a tutorial much better than this.
  • use the trinary operator: (condition)?foo:bar;

JAPH

Just Another Perl Hacker

Decoding JAPH from a transposed string literal:

$_="krJhruaesrltre c a cnP,ohet";$_.=$1,print$2while s/(..)(.)//;

Printing out JAPH as separate processes:

for $i (0..4) { if (!fork) {
      $i == 0 or not { $SIG{INT} = sub { print "J" } } or
      $i == 1 or not { $SIG{INT} = sub { print "A" } } or
      $i == 2 or not { $SIG{INT} = sub { print "P" } } or
      $i == 3 or not { $SIG{INT} = sub { print "H" } } ;
      sleep $i; last; } } kill INT => $$;

Appearing as if it does something completely unrelated to printing JAPH:

$_ = "wftedskaebjgdpjgidbsmnjgc";
tr/a-z/oh, turtleneck Phrase Jar!/; print;

Using only punctuation, no alphanumeric characters (written by Eric Roode; only works on Unix and Unix-like systems):

`$=`;$_=\%!;($_)=/(.)/;$==++$|;($.,$/,$,,$\,$",$;,$^,$#,$~,$*,$:,@%)=(
$!=~/(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)......(.)/,$"),$=++;$.++;$.++;
$_++;$_++;($_,$\,$,)=($~.$"."$;$/$%[$?]$_$\$,$:$%[$?]",$"&$~,$#,);$,++
;$,++;$^|=$";`$_$\$,$/$:$;$~$*$%[$?]$.$~$*${#}$%[$?]$;$\$"$^$~$*.>&$=`

subs [1]:

print sub { sub { sub { sub { join ' ', @_ } -> (@_, 'Hacker') } 
-> (@_, 'Perl') } -> (@_, 'Another') } -> ('Just');



Nifty Perl Encoded Message

This outputs "RTFM". [2]:

perl -e 'print $i=pack(c5,(41*2),sqrt(7056),(unpack(c,H)-2),oct(115),10);'

Perl Camel

Perl Camel - The Coded Camel - Cool Linux And Unix Perl Art

Media:Perl Camel.jpg

Kenneth's encoded message

I know, it's geeky, but it means more because I spent time encoding it, right?
perl -e 'for("077101114114121032067104114105115116109097115010"=~/.../g){print chr}'
Merry Christmas

Visual Programming in Perl

Acme::EyeDrops - Visual Programming in Perl

Sierpinski Triangles

Sierpinski Triangles

Perl Sierpinski Triangles Generator:

#!perl -l
$x=2**pop;print$"x--$x,map$x&$_?$"x2:"/\\",0..$y++while$x
$ perl sierpinski_triangles.pl 4
               /\
              /\/\
             /\  /\
            /\/\/\/\
           /\      /\
          /\/\    /\/\
         /\  /\  /\  /\
        /\/\/\/\/\/\/\/\
       /\              /\
      /\/\            /\/\
     /\  /\          /\  /\
    /\/\/\/\        /\/\/\/\
   /\      /\      /\      /\
  /\/\    /\/\    /\/\    /\/\
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

Perl Code

Common Pragma

Note: For clarity, the following examples contain basic Perl code snippets which do not use my or other recommended practices. For happy Perl programming always use the pragma

use strict;
use warnings;

at the start of your scripts.

Source: Perl DBI examples (DBD::mysql)

System Call

@result = `wc -l /etc/passwd`;
print "Number of Lines: @result\n";
print "Return value: $?\n";
system "cmd", "arg1", "arg2", ...;
exec "wc -l /etc/passwd";

Try/Catch with Eval

eval{
  ### try block
};  # notice the semi colon
if ($@){
  ### catch block
  print "Error: $@ \n";
};

Calling dynamic function

sub hello {
  print "hello";
}
$func = "hello";
&$func;

Flushing console buffer

$| = 1;
$|++;

Duping STDOUT

  print "STDOUT 1";
  warn "STDERR 1";
  print "STDOUT 2";
  warn "STDERR 2";

  # redirect standard output
  open my $oldout, ">&STDOUT" or die "Can't duplicate STDOUT: $!";
  open my $olderr, ">&STDERR" or die "Can't duplicate STDERR: $!";
  close STDOUT;
  open STDOUT, ">$log_file" or die "Can't redirect STDOUT: $!";
  close STDERR;
  open STDERR, ">>&STDOUT" or die "Can't redirect STDERR: $!";
  print "STDOUT 3";
  warn "STDERR 3";
  print "STDOUT 4";
  warn "STDERR 4";

  # restore the original standard output
  close STDOUT;
  open STDOUT, ">&$oldout" or die "Can't restore old STDOUT: $!";
  close STDERR;
  open STDERR, ">&$olderr" or die "Can't restore old STDERR: $!";

  print "STDOUT 5";
  warn "STDERR 5";
  print "STDOUT 6";
  warn "STDERR 6";

Source: Perl - Perl output redirection

Random Number

# random number
my $random_number = rand();
  0.521563085335405
# with range
my $random_number = rand($range);
  34.0500569277541
# integer
my $random_number = int(rand($range));
  68
# with offset
my $random_number = int(rand($range)) + $minimum;
  129
# documentation
perldoc -f rand

Source: Using the Perl rand() function

Dropping privileges

  1. permanently drops privs

($<,$>) = (getpwnam('nobody'),getpwnam('nobody'));

Source; It's Not Easy Being Omnipotent (Perl for System Administration)

Include Files

"Perl's equivalents of "include" are use, require and do." [3]

Perl Quote - Passing Forbidden Arguments

"Perl and I found a void context to pass forbidden arguments. After the shebang it was all standard error from there on. Careful where you put your Lexical."

-- Kenneth Burgener (March 16 at 9:55pm) on Facebook

Advanced Perl Topics

Modules

Module Search Path

Modules are search for in the @INC list. The current directory ('.') is generally included in this list.

@INC = ( @INC, "./lib");
require ABC::Test;

You can easily see what directories are assigned to the @INC array on your system with this code:

perl -e "print join(qq|\n|,@INC).qq|\n|"


A module referenced as:

use ABC::Test;

would be found as under:

ABC/Test.pm

Can use "Local" to avoid global modules (place all modules under ./Local/):

use Local::Test;

Locate modules not in standard locations:

use lib qw(/myPerl/myModules/);
use SayHello;

Can use 'require' to specify any file name to load. 'use' also loads modules at compile, where 'require' loads modules at runtime.

The Net::Telnet module is found here on my Cygwin system:

/usr/lib/perl5/vendor_perl/5.10/Net/Telnet.pm

Extending the library path

Option #1: Install the module somewhere in the standard library path

# list standard library path
perl -le 'print foreach @INC'

Option #2: Set the environment variable PERL5LIB

PERL5LIB=/home/path/lib:/usr/another/path/lib; export PERL5LIB

Note: Be aware that scripts running with -T option (taint checks) don't use that variable, so in those cases this option won't work.

Option #2: Use '-I' command line parameter

perl -I /home/path/lib -I /usr/another/lib script.pl

Option #3: Add the library path in your script

#!/usr/bin/perl
use lib "/home/path/lib";
use lib "/usr/another/lib";
use MyCustomModule;

Note: Notice that this statement prepends "path" to the @INC array, so it's basically the same as

unshift @INC, "path"

Reference: extending the library path | Perl HowTo

Basic Module

SayHello [4]

package SayHello;

our $VERSION=0.10;
# or cleaner code:
# $SayHello::VERSION = 0.10;

my $hello_string="Hello World!";

sub hello_message {
   return $hello_string;
}

1;
use SayHello;
# can check for version or higher:
# use SayHello 0.20;

# direct access to function
print SayHello::hello_message() . "\n";

# direct access to variable:
print $SayHello::VERSION . "\n";

Exporting Module

package SayHello;

use strict;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(hello_message);
# export by default:
# our @EXPORT = qw(hello_message);

our $VERSION=0.10;
my $hello_string="Hello World!";

sub hello_message {
    return $hello_string;
}

1;
#!/usr/bin/perl

use strict;
use SayHello qw(hello_message);

print "You are using version: $SayHello::VERSION of SayHello.\n";
print hello_message()."\n";

Complicated Module

A module generally starts with:

package ABC::Test;

use strict;
require 5.002;

## Module export
use vars qw(@EXPORT_OK);
@EXPORT_OK = qw(TEST1 TEST2 TEST_3);

## Module import
use Exporter ();

## Base classes
use vars qw(@ISA);
@ISA = qw(Exporter);

## Global variables
use vars qw($VERSION @MYOPTS);
$VERSION = "3.03";
@MYOPTS = ("OPT1", "OPT2");

sub new {
    my ($class) = @_;
    my (
        $errmode,
        $fh_open,
        $host,
        $self,
        %args,
        );
    local $_;

    ## Create a new object with defaults.
    $self = $class->SUPER::new;
    *$self->{net_telnet} = {
        bin_mode         => 0,
        blksize          => &_optimal_blksize(),
    };

    $self->func1;

    $self;
} # end sub new

sub DESTROY {
} # end sub DESTROY

sub func1 {
  ...
}

## Exported Constants ##
sub MYCONST1 ()     {255};
sub MYCONST2 ()     {1};

1;
__END__;


## USER DOCUMENTATION ##


## To format the following documentation into a more readable format,
## use one of these programs: perldoc; pod2man; pod2html; pod2text.
## For example, to nicely format this documentation for printing, you
## may use pod2man and groff to convert to postscript:
##   pod2man Net/Telnet.pm | groff -man -Tps > Net::Telnet.ps

=head1 NAME

Net::Telnet - interact with TELNET port or other TCP ports

=head1 SYNOPSIS

C<use Net::Telnet ();>

see METHODS section below

=head1 DESCRIPTION

Net::Telnet allows you to make client connections to a TCP port and do
network I/O, especially to a port using the TELNET protocol.  Simple
I/O methods such as print, get, and getline are provided.  More
sophisticated interactive features are provided because connecting to
a TELNET port ultimately means communicating with a program designed
for human interaction.  These interactive features include the ability
to specify a time-out and to wait for patterns to appear in the input
stream, such as the prompt from a shell.

Other reasons to use this module than strictly with a TELNET port are:

=over 2

=item *

You're not familiar with sockets and you want a simple way to make
client connections to TCP services.

=item *

You're not familiar with sockets and you want a simple way to make
client connections to TCP services.

=back

=over 4

=item B<cmd> - issue something

   Test

=back

=cut

CGI

Virtual Host:

<VirtualHost *:80>
    ServerName t0e.org
    ...
    AddHandler cgi-script .cgi
    <Directory />
        Options +ExecCGI
        AllowOverride All
    </Directory>
</VirtualHost>

helloworld.cgi:

#!/usr/bin/perl
print "Content-type: text/html\n\n";

print <<EOF
<html>
<body>

Hello World

</body>
</html>
EOF

Environment Variables:

$querystring = $ENV{QUERY_STRING}; 
my @values = split(/&/,$ENV{QUERY_STRING});
Name What it Gets
CONTENT_LENGTH Number of characters submitted from a POST command
HTTP_REFERER URL user came from, if available.
HTTP_USER_AGENT Type of Browser viewer is using, if available.
QUERY_STRING String in URL after the ? character
REMOTE_ADDR Remote user's IP address
REMOTE_HOST Name of user's host, if available.
SERVER_NAME Name of the local server, like: www.yoursite.com

References:

Sending Mail

$ENV{PATH} = "/usr/sbin";
open (MAIL, "|/usr/sbin/sendmail -t -oi") or 
   die "Can't fork for sendmail: $!\n";
# -t  	      	Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses
# -oi 	     	Ignore dots alone on lines by themselves in incoming messages.
my $recipient = 'recipient@cgi101.com';
print MAIL "From: sender\@cgi101.com\n";
print MAIL "To: $recipient\n";
print MAIL "Subject: Guestbook Form\n";
print MAIL "\n";
close(MAIL);

Reference:

Telnet

Using perl to connect to remote hosts via telnet.

use Net::Telnet;
$telnet = new Net::Telnet ( Timeout=>10, Errmode=>'die');
$telnet->open('camel.perlfect.com');
$telnet->waitfor('/login: $/i');
$telnet->print('bilbo');
$telnet->waitfor('/password: $/i');
$telnet->print('baggins');
$telnet->waitfor('/\$ $/i');
$telnet->print('who');
$output = $telnet->waitfor('/\$ $/i');
print $output;

Net::Telnet - interact with TELNET port or other TCP ports - search.cpan.org

use Net::Telnet ();
$t = new Net::Telnet (Timeout => 10,
  Prompt => '/bash\$ $/');
$t->open("sparky");
$t->login($username, $passwd);
@lines = $t->cmd("who");
print @lines;


Perl - FTP and Telnet Modules

Threads

perlthrtut - Tutorial on threads in Perl (perldoc.perl.org)

Your programs can use the Config module to check whether threads are enabled.

use Config;
$Config{useithreads} or die('Recompile Perl with threads to run this program.');

Example threaded program:

use threads;

@ParamList = (42, "Hello World");
my $thr = threads->create(\&sub1, @ParamList);

# To wait for a thread to exit and extract any values it might return, you can use the join() method:
my @ReturnData = $thr->join();
print('Thread returned ', join(', ', @ReturnData), "\n");
sub sub1 {
  my @InboundParameters = @_;
  print("In the thread\n");
  print('Got parameters >', join('<>', @InboundParameters), "<\n");
}

Synchronize with lock($var).

Note that there is no unlock() function - the only way to unlock a variable is to allow it to go out of scope.

Sleep

sleep $milisec;

Loop through all the threads

foreach my $thr (threads->list()) {
  $thr->join();
}

Shared data:

use threads::shared;
my $total :shared = 0;

Example with shared data and forced yields:

#!/usr/bin/perl -w

use strict;
use threads 'yield';
use threads::shared;

my $var : shared = 0;

sub tsub {
  my ($name) = @_;
  for(my $i = 1 ; $i < 10 ; $i ++ ) {
    yield();
    print "$name] $var\n";
    $var++;
    yield();
    # sleep random time
    select(undef,undef,undef,2 * (int(rand(100))/100) );
    yield();
  }
    return 0;
}

my $t1 = threads->new( \&tsub , "t1" );
my $t2 = threads->new( \&tsub , "t2" );
my $t3 = threads->new( \&tsub , "t3" );
my $t4 = threads->new( \&tsub , "t4" );
my $t5 = threads->new( \&tsub , "t5" );

# cleanup
my $retval;
$retval = $t1->join();
$retval = $t2->join();
$retval = $t3->join();
$retval = $t4->join();
$retval = $t5->join();

MySQL

Mysql example

perlinsertquery.pl:

#!/usr/bin/perl
#
# Source: http://www.tizag.com/perlT/perlmysqlquery.php
#

use Mysql;

print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "INSERT INTO 
$tablename (id, product, quantity) 
VALUES (DEFAULT,'pineapples','15')";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

# AFFECTED ROWS
$affectedrows = $execute->affectedrows($myquery);

# ID OF LAST INSERT
$lastid = $execute->insertid($myquery);

print $affectedrows."<br />";
print $lastid."<br />";

easyselectfunctions.pl:

#!/usr/bin/perl
#
# Source: http://www.tizag.com/perlT/perlmysqlquery.php
#

use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM $tablename";

# EXECUTE THE QUERY
$execute = $connect->query($myquery);

$rownumber = $execute->numrows();
$fieldnumber = $execute->numfields();

# PRINT THE RESULTS
print $rownumber."<br />";
print $fieldnumber."<br />";

fetchrow.pl:

#!/usr/bin/perl
#
# Source: http://www.tizag.com/perlT/perlmysqlquery.php
#

use Mysql;

print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM $tablename";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

# HTML TABLE
print "<table border='1'><tr>
<th>id</th>
<th>product</th>
<th>quantity</th></tr>";

# FETCHROW ARRAY

while (@results = $execute->fetchrow()) {
	print "<tr><td>"
	.$results[0]."</td><td>"
	.$results[1]."</td><td>"
	.$results[2]."</td></tr>";
}

print "</table>";

Source: Perl Tutorial - MySQL Query

DBD::mysql Example

Connect to MySQL:

use DBI;
$dbh = DBI->connect('DBI:mysql:databasename', 'username', 'password'
	           ) || die "Could not connect to database: $DBI::errstr";
# (insert query examples here...)
$dbh->disconnect();

Connect to a different host:

$dbh = DBI->connect('DBI:mysql:databasename;host=db.example.com', 'username', 'password',
	            { RaiseError => 1 }
	           );

Simple query:

$dbh->do('CREATE TABLE exmpl_tbl (id INT, val VARCHAR(100))');
$dbh->do('INSERT INTO exmpl_tbl VALUES(1, ?)', undef, 'Hello');
$dbh->do('INSERT INTO exmpl_tbl VALUES(2, ?)', undef, 'World');
$c = $dbh->do('DELETE FROM exmpl_tbl WHERE id=1');
print "Deleted $c rows\n";

Typical query:

$sth = $dbh->prepare('SELECT val FROM exmpl_tbl WHERE id=1');
$sth->execute();
$result = $sth->fetchrow_hashref();
print "Value returned: $result->{val}\n";

Query using placeholders:

$sth = $dbh->prepare('SELECT id FROM exmpl_tbl WHERE val=?',
undef, 'World');
@result = $sth->fetchrow_array();
print "ID of World is $result[0]\n";

Execute and fetch in one command:

$sth = $dbh->prepare('SELECT * FROM exmpl_tbl');
$results = $dbh->selectall_hashref('SELECT * FROM exmpl_tbl', 'id');
foreach my $id (keys %$results) {
  print "Value of ID $id is $results->{$id}->{val}\n";
}

Source: Perl DBI examples (DBD::mysql)

Big O Notation - Optimizing Your Perl

Perl.com: Optimizing Your Perl:

"Computer scientists and mathematicians use a system called big-O notation to describe the order of magnitude of how long something will take. Big-O notation represents a worst-case analysis.
If the runtime of a function is constant, then this is written as O(1). (Note the capital or "big" O.) Constant means that no matter how much data is processed, (i.e., how much input there is) the time doesn't change."
If the runtime is directly related to the amount of input (a.k.a. linear), then this is O(n). If there is twice as much input, then the algorithm will take twice as long to run. Some functions are O(n^2) (quadratic) or O(n^3) (cubic) or even worse."
Because we are only looking at orders of magnitude (is the operation going to take one minute or one hour) we can ignore constant factors and smaller terms. O(2n) and O(n) are equivalent. As are O(n+1) and O(n) or O(n^2+n) and O(n^2). The smaller term is insignificant compared to the larger.
There are rules for analyzing code and determining its big-O, but the simplest way is to look at how many times you iterate over the data. if you don't iterate, then it's O(1). If you iterate over it once, then it's O(n). If you have two nested loops, then it's probably O(n^2)."

Other references:


Recommended Perl Books

Perl Cookbook - Tips and Tricks for Perl Programmers

by Tom Christiansen, Nat Torkington
ISBN 10: 1-56592-243-3 | ISBN 13: 9781565922433
O'Reilly Media
August 1998
Pages: 794
Out of date

Perl Cookbook, Second Edition

By Tom Christiansen, Nat Torkington
August 2003
Pages: 964
ISBN 10: 0-596-00313-7 | ISBN 13: 9780596003135
Print $49.95
Print+Ebook $64.93
Ebook $39.99

Perl for Dummies (Third Edition)

(Paperback)
Amazon

Learning Perl, 5th Edition

(Paperback)
Amazon
Print $26.39
ISBN-10: 0596520107
ISBN-13: 978-0596520106
Paperback: 348 pages
Publisher: O'Reilly Media, Inc



Perl For System Administration Download

keywords

linux perl