Sie sind auf Seite 1von 22

Study Guide

1D0-437

CIW Perl Fundamentals


Perl Fundamentals (ID0-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)

The While Statement and The Do While Loop Statement .................................................................................. 11


The foreach Loop......................................................................................................................................................... 11
Syntax:............................................................................................................................................................................ 11
Loop Labels ................................................................................................................................................................. 11
Next .......................................................................................................................................................................... 11
Last........................................................................................................................................................................... 12
Redo ......................................................................................................................................................................... 12
Regular Expressions..................................................................................................................................................... 12
Pattern Matching and A Simple Regular Expression................................................................................................... 12
What is a Regular Expression? ................................................................................................................................ 12
Pattern matching options ............................................................................................................................................. 13
Metacharacters ............................................................................................................................................................ 13
What are Metacharacters? ....................................................................................................................................... 13
The Metacharacters ................................................................................................................................................. 13
Character Classes ....................................................................................................................................................... 14
What is a Character Class?...................................................................................................................................... 14
Remember that you can not use a quantifier within a class..................................................................................... 14
Quantifiers.................................................................................................................................................................... 14
What is a Quantifier?................................................................................................................................................ 14
Assertions .................................................................................................................................................................... 14
The =~ Operator .......................................................................................................................................................... 15
Subroutines.................................................................................................................................................................... 15
Defining A Subroutine .................................................................................................................................................. 15
What are Functions? (Subroutines) ......................................................................................................................... 15
Creating and using Subroutines .................................................................................................................................. 16
Creating a subroutine ............................................................................................................................................... 16
Pass a list to a Subroutine........................................................................................................................................ 16
Hashes ............................................................................................................................................................................ 16
What is a Hash?........................................................................................................................................................... 16
Hash Syntax ............................................................................................................................................................. 17
The values, keys, and each Function .......................................................................................................................... 17
Values Function........................................................................................................................................................ 17
Keys Function........................................................................................................................................................... 17
Each Function .......................................................................................................................................................... 18
Environment Variables.................................................................................................................................................. 18
What are Environment Variables? ............................................................................................................................... 18
Common Environment Variables ................................................................................................................................. 18
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.

Some of Perls biggest strengths are:


It can use sophisticated pattern-matching techniques to scan very large amounts of data quickly
It can also work with binary data

To get a copy of Perl, visit the links section of this Cramsession.

Basic Syntax for PERL


Basic Rules
A Line MUST start with a token that doesnt expect a left operand.
A Line MUST be terminated with a semicolon.
(The only exception to the above rule is if it is the last line in a block.)
If splitting a line in a quoted string, line termination will become part of the string.

Writing Scripts
Syntax: (Unix)
Perl Newscript.pl
Perl Fundamentals (ID0-437)

On the other hand, you can also use it for Windows:


C:\> Perl Newscript.pl

Extract Source code


(Using tar and Gunzip)
Gunzip c perl.tar.gz | tar xvf -

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)

Expression Operators and Syntax


Operators
You should remember that data needs to be modified or manipulated in order for you to have programs that are useful
and operators are used for that function. Perl contains many operators to do that job.

Operator types
Below is a list of types along with a brief explanation (including syntax, where they should apply, and where they are
applicable):

Arithmetic operators Used with addition and subtraction / standard math

Relational operators Compare how data items relate to one another

Logical operators These are used to test if the data is true or false

Bitwise operators & (And), | (OR), and ^ (XOR) or Exclusive Or

Binding operators Used to bind the results of a pattern match

Range operator Used to refer to a range of numbers (if used in Scalar context,
then Boolean)

Conditional operator Used as a replacement for if / then / else

Note: There are also other operators available.

Arithmetic operators

->

++--

**

=~ !~

*/%x

+-
Perl Fundamentals (ID0-437)

<<>>&&

?:

Not

And

Relational operators

Operators Basic meaning

> or gt Greater than

< or lt Less than

>= or ge Greater than / equal to

<= or le Less than / equal to

== or eq Equal to

!= or ne Not equal to

< = > or cmp This is a comparison

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)

Using the stat and lstat Functions


Stat
Will return a 13 element array that gives a status on a file
Values returned by stat:

0 Device Number of file system

1 Inode Number

2 File Mode

3 Number of Hard links to file

4 Numeric User ID

5 Numeric Group ID

6 The Device Identifier

7 File Size (Bytes)

8 Last Access (Since epoch)

9 Last Modify time (Since epoch)

10 Inode Change time

11 Preferred Block Size for I/O

12 Number block allocated (actual #)

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)

The for, while, and do while Loop Statements


The For Statement
The For loop is like a while loop with an added expression. This added expression is used for reevaluation of the
original conditional expression.

The While Statement and The Do While Loop Statement


You will normally see this as the Do / While / Until loop statement.
Just like English, you would make a statement that will DO something while something else is going on.

Syntax:
Do {
Statement_1;
Statement_2;
} While Some_Expression;

Remember that the inverse of the While loop is the until loop.

The foreach Loop


This statement will take a list of values and will assign each one, one at a time.

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.

Lets look at perl Syntax:


If (/gz/) {
Print $_;
}
Again, gz is the regular expression that is tested. Remember that a regular expression is a pattern.

Pattern matching options

G Match all the possible patterns

I Ignore the case

M Handle the string as multiple lines

S Handle string as single line

X Ignore white space

O Evaluate once only

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)

Here are a few examples of Assertions:

(?=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

Note: There are many more.

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.

Functions are: the built in subroutines within Perl to add functionality.


Perl Fundamentals (ID0-437)

Creating and using Subroutines


Creating a subroutine
You create a subroutine with the word "sub".
Lets make a simple subroutine:

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".

Pass a list to a Subroutine


Syntax:
Mynewsub (A,B,C);
@xxx = (B,C);
Mynewsub (A, @xxx);
@xxx = (A,B,C);
Mynewsub (@xxx);

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",
)

The values, keys, and each Function


Values Function
The values function will return the value assigned to a hash array.

Syntax:
%Certgrades = (
CIW => "100",
Novell => "90",
MS => "80",
Cisco => "70",
);

@Certs = Values (%Certgrades);


Print @Certs; # prints 801009070

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)

Cisco => "70",


);

Print keys (%Certgrades); # prints CIWNovellMSCisco

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.

Common Environment Variables


HOME
This is the home directory for the script.
If an argument is not specified, it is used by chdir.

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>

What else can you do?


Examine the symbol table
Get stack backtraces
Check variable values
Set breakpoints
Other operations typically found in debuggers

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 Lower case w


This switch is responsible for PRINTING out warnings about possible typographical errors in your script.

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).

Using a Database Driver and Connecting to a Database


The database driver is usually a C++ API that will in turn communicate directly to the actual database itself.
The process of connecting to an actual database can be the result of a few steps:

Open the connection to the database (DB)


Syntax:
Use DBI;
My $dbn = DBI->connect (DSN);
Note: DSN is the Data Source Name
Perl Fundamentals (ID0-437)

Perform a query to the DB


The DO method is used to execute a query.

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();

Structured Query Language Commands


For a full white paper on SQL architecture, visit Technet.
Fundamentals of SQL Server Architecture

The SQL SELECT and INSERT Statements


SELECT
Used when you want to extract information from the database.
Select will retrieve sets of rows or columns from the DB and will return to you a dataset.

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

Das könnte Ihnen auch gefallen