Beruflich Dokumente
Kultur Dokumente
1D0-437
Table of Contents
Introduction to Perl ......................................................................................................................................................... 4
How is this guide laid out? ............................................................................................................................................. 4
What is Perl? .................................................................................................................................................................... 4
Practical Extraction and Report Language .................................................................................................................... 4
Basic Syntax for PERL................................................................................................................................................... 4
Basic Rules ................................................................................................................................................................ 4
Writing Scripts ............................................................................................................................................................ 4
Extract Source code ................................................................................................................................................... 5
Executing Scripts........................................................................................................................................................ 5
Print ............................................................................................................................................................................ 5
Scalar ............................................................................................................................................................................. 5
Scalar Function .......................................................................................................................................................... 5
Numerical context .......................................................................................................................................................... 5
String context ................................................................................................................................................................. 6
Remember that:.......................................................................................................................................................... 6
Expression Operators and Syntax ................................................................................................................................. 6
Expression Operators and Syntax ................................................................................................................................. 7
Operators.................................................................................................................................................................... 7
Arithmetic operators ................................................................................................................................................... 7
Relational operators ................................................................................................................................................... 8
File I/O............................................................................................................................................................................... 8
What is a Filehandle? .................................................................................................................................................... 8
Using the stat and lstat Functions................................................................................................................................. 9
Stat................................................................................................................................................................................. 9
Lstat ............................................................................................................................................................................... 9
Using <STDIN>................................................................................................................................................................. 9
Flow Control................................................................................................................................................................... 10
Boolean Expressions ................................................................................................................................................... 10
What is Boolean? ..................................................................................................................................................... 10
The if Statement........................................................................................................................................................... 10
If ($study == $today)...................................................................................................................................................... 10
Loops ........................................................................................................................................................................... 10
Loop Statements ...................................................................................................................................................... 10
The for, while, and do while Loop Statements............................................................................................................. 11
The For Statement ................................................................................................................................................. 11
Perl Fundamentals (ID0-437)
HOME....................................................................................................................................................................... 18
PATH ........................................................................................................................................................................ 18
PERLLIB................................................................................................................................................................... 19
Debugging Perl .............................................................................................................................................................. 19
Debugging.................................................................................................................................................................... 19
What else can you do?............................................................................................................................................. 19
The W Switch............................................................................................................................................................. 19
The Lower case w .................................................................................................................................................. 20
The Uppercase -W ................................................................................................................................................... 20
Database Connectivity .................................................................................................................................................. 20
Benefits of Using Databases........................................................................................................................................ 20
Database Fundamentals.............................................................................................................................................. 20
The Database Interface Module (DBI) ..................................................................................................................... 20
Using a Database Driver and Connecting to a Database............................................................................................ 20
Open the connection to the database (DB).............................................................................................................. 20
Perform a query to the DB........................................................................................................................................ 21
Close DB connection................................................................................................................................................ 21
Structured Query Language Commands ..................................................................................................................... 21
The SQL SELECT and INSERT Statements ............................................................................................................... 21
SELECT.................................................................................................................................................................... 21
INSERT .................................................................................................................................................................... 21
Perl Fundamentals (ID0-437)
Introduction to Perl
How is this guide laid out?
To learn Perl, all you need is a web browser, Perl and some time. All you need to know is available on the Internet.
You could purchase a book or a HOW TO but if you are already familiar with the Language, then you will be prepped
for this exam with the online notes. The Perl program and libraries are free and you can download them from the links
section. You can also look at the MAN pages (A set of manuals that are free) to learn Perl and use it. This study Guide
is mapped to those pages. Please follow the links provided within the guide and links section for systematic HOW
TOs from the makers and supporters of Perl. Most info can be found here: Perl.com.
What is Perl?
Practical Extraction and Report Language
Developed by Larry Wall.
Perl is a language used for:
Scanning text files
Extracting information from those text files
Printing a report based on the extracted information
It's also a good language for many system management tasks and is heavily used by the Unix community as well as
the Windows and Apple communities.
Writing Scripts
Syntax: (Unix)
Perl Newscript.pl
Perl Fundamentals (ID0-437)
Executing Scripts
Perl newscript.pl #!/usr/local/bin/perl
Print
The Print Function prints the values of expressions in LIST to what is the current default Filehandle.
If it is set, then a variable will be added to the end of LIST.
The variable is $\
Now remember that if LIST is empty, then a different variable is added.
The variable is then $_
It is better to use print within a large LIST context.
Scalar
Scalar Function
A Scalar function can be either a number or a character string that can be acted upon by operators
The scalar function will force the evaluation of EXPR to be in scalar context and can do this even when it would work
normally in the LIST context.
Remember that there are two basic contexts:
Scalar
List
Syntax: (Scalar)
$Size = @list;
Syntax: (List)
Sort @list;
Numerical context
Is context that is pointed out Numerically.
You can have numbers, float literals, and integer literals.
Perl Fundamentals (ID0-437)
String context
Alternatively, just Strings are sequences of characters as mentioned above.
There are no characters in the shortest possible string.
You can have single or double quoted strings.
Remember that:
A Scalar is a simple data type
A Scalar Context is the environment where an expression expects to return a scalar
A Scalar Literal is an actual value that is a scalar (other is scalar variable)
A Scalar Variable is a variable that holds a scalar value
A Scalar Value is a value that is scalar (other is a List value)
A List Value is a list of scalar values that, when passed, will provide a list context
A List context is an environment where an expression returns a list not a single value
A List operator is an item that does operations to a list
Perl Fundamentals (ID0-437)
Operator types
Below is a list of types along with a brief explanation (including syntax, where they should apply, and where they are
applicable):
Logical operators These are used to test if the data is true or false
Range operator Used to refer to a range of numbers (if used in Scalar context,
then Boolean)
Arithmetic operators
->
++--
**
=~ !~
*/%x
+-
Perl Fundamentals (ID0-437)
<<>>&&
?:
Not
And
Relational operators
== or eq Equal to
!= or ne Not equal to
File I/O
What is a Filehandle?
Perl sends data to output devices (monitor) and receives data from input devices (mouse). These I/O channels are
called FILEHANDLES.
There are two FILEHANDLES:
STDIN
STDOUT
There are also predefined FILEHANDLES for I/O errors in STDERR.
Perl Fundamentals (ID0-437)
1 Inode Number
2 File Mode
4 Numeric User ID
5 Numeric Group ID
Lstat
Performs same tests as in stat but, if the file is a symbolic link, it will return the info for the link instead of the file that it
points to.
Using <STDIN>
STDIN (Standard Input) is the input stream for your Perl scripts while STDOUT is for Standard Output.
The <STDIN> operator is very helpful. It is used when a user, who is using Perl, is prompted with this operator to
provide input.
When you run a simple program with the <STDIN> operator, user input is required.
Syntax:
Print Cramsession Rules the World;
$Input = <STDIN>;
Print $input;
Perl Fundamentals (ID0-437)
Note: This would show the top line of this code when ran.
Flow Control
Boolean Expressions
What is Boolean?
Boolean manifests itself in an expression that is solely used to identify a
TRUE or a FALSE value.
The if Statement
The If statement is a conditional statement that allows you to control the
execution of your script.
It is basically designed just like the English word if and it functions much
like asking a question if the statement is true, it will execute that block of
code
Syntax:
Print Cramsession will help you with your studies\n if ($study == $today);
If ($study == $today)
{
Print Cramsession will help you with your studies\n;
}
Loops
Loop Statements
Perl can support four basic loop types:
for
while
until
foreach
With each usage, the loop execution will continue until evaluation of a
supplied expression has changed. Lets look at the testable types below:
Perl Fundamentals (ID0-437)
Syntax:
Do {
Statement_1;
Statement_2;
} While Some_Expression;
Remember that the inverse of the While loop is the until loop.
Syntax:
Foreach (@days)
{
Print $_\n;
}
Loop Labels
Loop Labels can be applied to loops or blocks. When you assign a loop label, you are giving your loop a name. You
can have keywords for loop control and it is used with Next, last and redo loop control keywords:
Next
Next will skip remainder of the code block, which forces the loop to go to the next value.
Syntax:
While (< >)
{
Next if /^#/;
Perl Fundamentals (ID0-437)
Last
Last, will end the loop completely.
Syntax:
While (< >)
{
Last if ($xx);
}
Redo
Redo will re-execute the code and not reevaluate the conditional statement.
Syntax:
While (< >)
{
If (s#\\$#)
{
$_ .= < >;
Redo;
}
}
Regular Expressions
Pattern Matching and A Simple Regular Expression
What is a Regular Expression?
A Regular Expression is a pattern (or a template) that is matched against a string.
This is commonly used with Unix commands.
Syntax:
grep gz
We are trying to grep or rake through the directory to find anything with a gz in it.
Perl Fundamentals (ID0-437)
We are using grep to test against each line to find the regular expression gz and any line that matches is sent
standard output.
Metacharacters
What are Metacharacters?
Metacharacters define the 12 main characters that are used to define major components of regular expressions
syntax.
The Metacharacters
\ ^
| $
( *
) +
[ ?
{ .
Perl Fundamentals (ID0-437)
Character Classes
What is a Character Class?
Character classes will allow you to specify a list of values for one single character.
Syntax:
If ($name =~ / [Cc]ramsession/)
Notice in the [] Metacharacters you have a big C and a little c. In addition, within the brackets you can specify a range.
Remember that you can not use a quantifier within a class.
Quantifiers
What is a Quantifier?
A Quantifier is a special character or a sequence that will define the number of times the previous character or
sequence appears.
Assertions
What are Assertions?
Regular Expressions also allow you to be specific about a number of additional extensions (these are assertions in the
main expression and they enable more specific matches to take place).
Perl Fundamentals (ID0-437)
(?=Pattern) Matches if the regular expression would match PATTERN next and
does not affect the overall result
(?!Pattern) Matches if the regular expression would NOT match PATTERN next
and does not affect the overall result
(?<=Pattern) Matches if the next statement would have matched the regular
expression
The =~ Operator
Remember that certain operations will, by default, search or modify the string "$_".
The =~ operator makes that kind of operation work on some other string.
The argument on the right side is:
Search pattern
Substitution
Translation
The argument on the left side is what is supposed to be searched, substituted, or translated instead of the default "$_".
The value returned will indicate the success of the operation.
Subroutines
Defining A Subroutine
What are Functions? (Subroutines)
A Subroutine is an item used to perform a function on a variable and to do so many times.
The words function and subroutines are used interchangeably.
Subroutines are: small pieces of named blocks that accept arguments and return values.
Syntax:
Print &sum (4,4);
Sub sum {
$sum = 0;
Foreach $num (@_)
{
$sum += $num;
}
Return $sum;
}
Remember: if you use the "&" symbol, it is required only when there is ambiguity.
To return a value from a subroutine, use the keyword "return".
Hashes
What is a Hash?
Hashes can be thought of as an advanced form of an Array where an array is a bunch of scalars. A limitation with an
Array is that it is hard to get at the data within. Hashes are neater and allow you to view specific items or access items
by scalar key. A Hash is cool because you dont have to reference the entire hash, just reference one of its elements
Perl Fundamentals (ID0-437)
Hash Syntax
Common Syntax includes:
A hash variable name is the percent sign (%) followed by a letter.
Lets make a simple hash based on passed certification exams:
Syntax:
%Certgrades = (
CIW => "100",
Novell => "90",
MS => "80",
Cisco => "70",
)
Syntax:
%Certgrades = (
CIW => "100",
Novell => "90",
MS => "80",
Cisco => "70",
);
Keys Function
The keys function will return the list of keys in the hash array.
Syntax:
%Certgrades = (
CIW => "100",
Novell => "90",
MS => "80",
Perl Fundamentals (ID0-437)
Each Function
The Each Function returns each key value pair of the hash array.
Syntax:
%Certgrades = (
CIW => "100",
Novell => "90",
MS => "80",
Cisco => "70",
);
While (($name, $cert( = each (%Certgrades)) {
Print $name: $cert\n;
}
Environment Variables
What are Environment Variables?
The shell you are using usually automatically set up environment variables
(this goes for Unix, Windows, etc.). Setting these variables can change
certain elements of Perl.
PATH
Is the listing of directories that is searched.
Used with the S command line switch.
Perl Fundamentals (ID0-437)
PERLLIB
Is the listing of directories (colon separated) that is used to look for Libraries or modules that are used by Perl.
Note: There are MANY environment variables, in Perl, Unix, and Windows.
e.g., Windows uses the variable %systemroot% to produce the WINNT directory in NT
Debugging Perl
Debugging
To check and evaluate code, it needs to be debugged. Entire 400 page manuals cover the debugging of Perl or any
other version of code. Lets look at the basic syntax:
Basic Syntax:
To start
Perl -de 42
Note: I am using the win32 version on Windows.
Now just type in any legal Perl code and it will be immediately evaluated.
Syntax:
D:\Perl>perl -de 42
Default die handler restored
Loading DB routines from perl5db.pl version 1.07
Editor support available
Enter h or `h h' for help, or `perldoc perldebug' for more help
Main::(-e:1): 42
DB<1>
The W Switch
Used to turn Warnings on with a script.
You should be aware that there are two versions of this switch (the Upper and lower case versions) w and W.
Perl Fundamentals (ID0-437)
The Uppercase -W
This switch is responsible for enabling all warnings.
Syntax:
#! Perl -W
Database Connectivity
Benefits of Using Databases
A Database is a collection of information specifically organized so that a computer program can quickly select and
manipulate queried data. You can think of a database as an electronic filing system or an electronic filing cabinet that
neatly holds your data. Traditional databases are organized by fields, records, and files while relational databases are
related pieces of data that are grouped together in a single structure or record, and relationships can be defined
between these structures and records. Databases can also be placed behind a firewall making them more secure,
audited and heavily monitored for wrongdoing.
Having all your data in one place also allows consistent and thorough backup with a god backup solution.
Database Fundamentals
The Database Interface Module (DBI)
What is the DBI?
The DBI toolkit is a grouping of methods that you can use to allow you to connect to and execute queries to a
database. The DBI module communicates with the Database Driver (explained below).
Syntax:
$dbn->do
Close DB connection
To disconnect you can use the following syntax to manually close the connection because you need to do it manually
because it is not automatically done.
Syntax:
$dbn->disconnect();
Syntax:
SELECT [all or distinct] field
FROM table
ORDER BY field [asc or desc]
Note: All is used to select everything but will pull duplicates. Use Distinct to specify and you can specify the ascending
or descending order.
INSERT
The Insert command will ADD a row to the table.
Syntax:
INSERT INTO table
VALUES