Perl

Great scripting language with an enormous support on the web and a
huge number of modules to support you writing pretty complex
things. There are several posts with nice examples of code.
External links:

Module handling

perl -MCPAN -e shell
Start module CPAN and enter its shell (Command Line Interface)

Then, after your configured cpan:

cpan> Install Bundle::CPAN
Install the bundle cpan.
cpan> i /search term/
Search modules
/usr/bin/perl -MCPAN -e
‘CPAN::Shell->install(CPAN::Shell->r)’
Auto update your installed modules.

Perl syntax

@array = qw(element1 element2 element3);
@array = qw/element1 element2 element3/;
All elements are automatically quoted.
undef @array;
Undefine an array
$var = @array
The number of elements in an array
($var) = @array
The contents of an array.
$array[1]
Addresses the second element of an array.
@array[0,3]
Addresses the first and the fourth element of an array
@array[1..3]
Addresses the second up to the fourth element of an array (element 2,3 and 4)
@_
Default array, if no array is specified it may very well be in @_. E.g. in functions use ‘($var1, $var2) = @_; to catch the passed parameters.’
@ARGV
Array holding the commandline arguments
@array = split(‘/’,$string)
Split $sting on / and put the elements into @array
%Hash = ();
Define empty hash. A hash is an array where elements have a name, not just a number. You can create multi-dimensional arrays very easy.
$Hash{$x}{$y}{$z} = ‘blabla’
Create 3 dimensional Hash and put ‘blabla’ in location $x,$y,$z.
for ( $x=0 ; $x <= 100 ; $x++ ) { block}
Block is executed while x <=100, x starts at 0 and is increased by 1 after each loop.
$|++;
This line forces output to be written immediate. Normally perl only writes output after a newline or when buffers get full.
sort
Sort the following array natural (numeric if all elements are numeric, alphanumeric if else). E.g. foreach $key (sort (keys (%hash)))
sort {$a cmp $b}
force alphanumeric sort
sort {$b <=> $a)
sort descending (force numeric)
$a = $var++
First assign $var to $a, then increase $var by 1
$a = ++$var
First increase $var by 1, then assign $var to $a

Special Variables

Per filehandle Variable

$%
Current page number
$=
Current page length
$-
Number of lines left on the page
$
Name of the current report format
$^
Name of the current top-of-page format

Local Special Variables

These variables are local to the current block. All of  them are associated with the last successful pattern match.

$1..$9
Contains the subpattern from the corresponding set of parentheses in the last pattern matched
$&
Contains the string matched by the last pattern match
$`
The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already.
$’
The string following whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already. For example:
$_ = ‘abcdefghi’;
/def/;
print “$`:$&:$’n”;
# prints abc:def:ghi
$+
the last bracket matched by the last search pattern. This is useful if you don’t know which of a set of alternative patterns matched. For example:
/Version: (.*)|Revision: (.*)/
&& ($rev = $+);

Global Special Variables

There are quite a few variables that are global in the fullest sense — they mean the same thing in every package. If you want a private copy of one of them, you must localize it in the current block.

$_
Default input, output, pattern matching space. Whatever you do, the result is most times in $_. The following pairs are equivalent:

while (<>) {… while ($_ =<>) {…
/^Subject:/ $_ =~ /^Subject:/
y/a-z/A-Z/ $_ =~ y/a-z/A-Z/
chop chop($_)
$.
The current input line number of the last filehandle that was read. Remember that only an explicit close on the filehandle resets the line number.
$/
The input record separator, newline by default. $/ may be set to a value longer than one character in order to match a multi-character delimiter. If $/ is undefined, no record separator
is matched, and <FILEHANDLE> will read everything to the end of the current file.
$
The output record separator for the print operator. You set $ instead of adding n at the end of the print.
$,
The output field separator for the print operator. What is printed when there is a , in
your print statement
$”
This is similar to $, except that it applies to array values interpolated into a double-quoted string (or similar interpreted string). Default is space.
$#
The output format for numbers display via the print operator #is the number sign
$$
The process number of the Perl running this script Same as shells
$?
The status returned by the last pipe close, backtick(“) command or system operator. Note that this is the status word returned by the wait() system call, so the exit value of the subprocess is actually ($? >>*). $? & 255 gives which signal, if any, the process died from, and whether there was a core dump.Similar to sh and ksh
$*
Set to 1 to do multi-line matching within a string, 0 to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Default is 0* matches multiple things
$0
Contains the name of the file containing the Perl script being executed. Depending on your OS, it may or may not include the full pathname.Same as sh and ksh
$[
The index of the first element in an array, and of the first character in a substring.[ begins subscripts
$]
The first part of the string printed out when you say perl -v. It can be used to determine at the beginning of a script whether the Perl interpreter executing the script is in the right range of versions.
If used in a numeric context, $] returns version + patchlevel /1000.Is this version of Perl in the
rightbracket”?
$;
The subscript separator for multi-dimensional array emulation. If you refer to an associative
array element as: $foo{$a,$b,$c} it really means: $foo{join($;, $a, $b, $c)} but don’t put @foo{$a,$b,$c} which means ($foo{$a},$foo{$b},$foo{$c}) Comma (the syntactic subscript
separator) is a semi-semicolon.
$!
If used in a numeric context, yields the current value of errno, with all the usual caveats. (This means that you shouldn’t depend on the value of $! to be anything in particular unless you’ve gotten a specific error return indicating a system error.) If used in a string context, yields the
corresponding sysem error string.
$@
The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.Where was the syntax error at?

File Handling

open (FH, < $filename);
Open file $filename for read on FileHandle FH. > opens for
output, >> for append
<STDIN>
Filehandle for standard input. You don’t have to open STDIN
yourself.
($Directory, $Filename) = $FullPath =~ m/(.*/)(.*)$/;
Split a full path in directory and filename
use File; @files = File::Find::Rule->file->not_symlink
->extras({ follow => 1 }) ->maxdepth(2) ->name( ‘*.jpg’
) ->in(‘<path1>’,'<path2>’ );
Fills the @files array with the found files in locations
<path1> and <path2>
opendir DIR, $indir; @FILES=grep(!/^..?$/,readdir(DIR));
Fill array @FILES with filenames of all files in $indir not
starting with . or ..
undef $/;
Undefine EOL definition, default $/ = ‘n’.
$file = <FH>;
Read the file into $file. Use this if $/ is undefined. The
complete file opened on filehandle FH is in $file, you can handle
it as one string now.
@lines = <FH>;
Read the file into @lines. Use this If $/ is defined. Each line
will be an element in the array @lines

Database handling

$dbh = DBI->connect(“DBI:mysql:
database=$serverDb; host=$serverName; port=$serverPort;
user=$serverUser; password=$serverPass”); $dbh->disconnect;
Open and close a database connection. In between do something like below
$SQL = “select ID,Location from Foto where Location = ‘$Location'”;
$cursor = $dbh->prepare($SQL);
$cursor->execute();
while ( ($ID, $location) = $cursor->fetchrow ) {
push(@Locations,$location);
push(@IDs,$ID);
}
$cursor->finish;
Execute sql and put the result in arrays
use CGI;
my $q = CGI->new; my $par = $q->param (“par”);
Get a parameter from a URL like http://test.pl?par=blabla

Matching

if an defined but empty value is provided it does match /^$/
(start, end and nothing in between) it does not match ” (single
quotes with nothing in between). Empty values do match ” after it
passed a substitute command =~ s/<old>/<new>/, even if
nothing is replaced.

Examples Code

I created a  template environment to support maintainable code.

This script adds an item to a rrd-database. rrd-add-item

Script to dump mySQL databases to CSV-files

Rewrite any wellformed XML-file as a easy readable file.

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.