Check out these great features at www.cramsession.com > Discussion Boards http://boards.cramsession.com
Your Trusted
S...
11 downloads
372 Views
496KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Check out these great features at www.cramsession.com > Discussion Boards http://boards.cramsession.com
Your Trusted
Study Resource for Technical Certifications Written by experts. The most popular study guides on the web. In Versatile PDF file format
> Info Center http://infocenter.cramsession.com
> SkillDrill http://www.skilldrill.com
> Newsletters http://newsletters.cramsession.com/default.asp
> CramChallenge Questions http://newsletters.cramsession.com/signup/default.asp#cramchallenge
> Discounts & Freebies http://newsletters.cramsession.com/signup/ProdInfo.asp
CIW Perl Fundamentals Version 3.0.0
Notice: While every precaution has been taken in the preparation of this material, neither the author nor Cramsession.com assumes any liability in the event of loss or damage directly or indirectly caused by any inaccuracies or incompleteness of the material contained in this document. The information in this document is provided and distributed "as-is", without any expressed or implied warranty. Your use of the information in this document is solely at your own risk, and Cramsession.com cannot be held liable for any damages incurred through the use of this material. The use of product names in this work is for information purposes only, and does not constitute an endorsement by, or affiliation with Cramsession.com. Product names used in this work may be registered trademarks of their manufacturers. This document is protected under US and international copyright laws and is intended for individual, personal use only. For more details, visit our legal page.
CIW Perl Fundamentals
CIW Perl Fundamentals Version 3.0.0
Abstract: This study guide will help you to prepare for exam 1D0-437, CIW Perl Fundamentals. Exam topics include: Perl syntax, using regular expression, using Perl data types, accessing and manipulating files, and database connectivity and debugging techniques.
Find even more help here:
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 1
CIW Perl Fundamentals
Contents: Introduction to Perl ........................................................................................ 6 How is this guide laid out? ............................................................................ 6 What is Perl? ................................................................................................. 6 Practical Extraction and Report Language ....................................................... 6 Basic Syntax for PERL .................................................................................. 6 Basic Rules .............................................................................................. 6 Writing Scripts ......................................................................................... 7 Extract Source code .................................................................................. 7 Executing Scripts...................................................................................... 7 Print ....................................................................................................... 7 Scalar........................................................................................................ 7 Scalar Function ........................................................................................ 7 Numerical context ....................................................................................... 7 String context............................................................................................. 8 Remember that:....................................................................................... 8 Expression Operators and Syntax .................................................................. 8 Operators ................................................................................................ 8 Arithmetic operators ................................................................................. 9 Relational operators .................................................................................. 9 File I/O......................................................................................................... 9 What is a Filehandle? ................................................................................... 9 Using the stat and lstat Functions....................................................................10 Stat..........................................................................................................10 Lstat ........................................................................................................10 Using <STDIN> ............................................................................................10 Flow Control .................................................................................................11 Boolean Expressions ...................................................................................11
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 2
CIW Perl Fundamentals What is Boolean? .....................................................................................11 The if Statement ........................................................................................11 If ($study == $today) ...................................................................................11 Loops .......................................................................................................11 Loop Statements .....................................................................................11 The for, while, and do while Loop Statements.................................................11 The “For” Statement ................................................................................11 The “While” Statement and The “Do While Loop” Statement ..........................11 The foreach Loop .......................................................................................12 Syntax: .......................................................................................................12 Loop Labels ...............................................................................................12 Next ......................................................................................................12 Last .......................................................................................................12 Redo......................................................................................................13 Regular Expressions ......................................................................................13 Pattern Matching and A Simple Regular Expression .........................................13 What is a Regular Expression? ...................................................................13 Pattern matching options.............................................................................14 Metacharacters ..........................................................................................14 What are Metacharacters?.........................................................................14 The Metacharacters .................................................................................14 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 .................................................................................................15 The =~ Operator........................................................................................15 Subroutines .................................................................................................15
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 3
CIW Perl Fundamentals 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 ...........................................................................................16 The values, keys, and each Function .............................................................17 Values Function .......................................................................................17 Keys Function .........................................................................................17 Each Function .........................................................................................17 Environment Variables ...................................................................................18 What are Environment Variables? .................................................................18 Common Environment Variables ...................................................................18 HOME ....................................................................................................18 PATH .....................................................................................................18 PERLLIB .................................................................................................18 Debugging Perl .............................................................................................18 Debugging ................................................................................................18 What else can you do? .............................................................................19 The –W Switch...........................................................................................19 The Lower case –w ..................................................................................19 The Uppercase -W ...................................................................................19 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
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 4
CIW Perl Fundamentals Open the connection to the database (DB) ..................................................20 Perform a query to the DB ........................................................................20 Close DB connection ................................................................................21 Structured Query Language Commands.........................................................21 The SQL SELECT and INSERT Statements ......................................................21 SELECT ..................................................................................................21 INSERT ..................................................................................................21
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 5
CIW Perl Fundamentals
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 TO’s” 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 Perl’s 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 doesn’t 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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 6
CIW Perl Fundamentals Writing Scripts Syntax: (Unix) Perl Newscript.pl 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”.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 7
CIW Perl Fundamentals You can have numbers, float literals, and integer literals. 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
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
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 8
CIW Perl Fundamentals context, then Boolean) Used as a replacement for if / then / else
Conditional operator
Note: There are also other operators available. Arithmetic operators -> ++-** =~ !~ */%x +<<>>&& . ?: Not And Relational operators Operators > or gt
Basic meaning Greater than
< or lt >= or ge <= or le == or eq != or ne < = > or cmp
Less than Greater than / equal to Less than / equal to Equal to Not equal to 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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 9
CIW Perl Fundamentals
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 1 2 3 4 5 6 7 8 9 10 11 12
Device Number of file system Inode Number File Mode Number of Hard links to file Numeric User ID Numeric Group ID The Device Identifier File Size (Bytes) Last Access (Since epoch) Last Modify time (Since epoch) Inode Change time Preferred Block Size for I/O 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; Note: This would show the top line of this code when ran.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 10
CIW Perl Fundamentals
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. Let’s look at the testable types below: 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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 11
CIW Perl Fundamentals 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 /^#/; } Last Last, will end the loop completely. Syntax: While (< >) { © 2001 All Rights Reserved – BrainBuzz.com 10/18/01 12
CIW Perl Fundamentals 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. 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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 13
CIW Perl Fundamentals Pattern matching options G I M S X O
Match all the possible patterns Ignore the case Handle the string as multiple lines Handle string as single line Ignore “white space” 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 \ | ( ) [ {
^ $ * + ? .
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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 14
CIW Perl Fundamentals 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). 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.
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 15
CIW Perl Fundamentals Creating and using Subroutines Creating a subroutine You create a subroutine with the word "sub". Let’s 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 don’t have to reference the entire hash, just reference one of its elements Hash Syntax Common Syntax includes: A hash variable name is the percent sign (%) followed by a letter. Let’s make a simple hash based on passed certification exams:
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 16
CIW Perl Fundamentals 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", Cisco => "70", ); Print keys (%Certgrades); # prints CIWNovellMSCisco Each Function The Each Function returns each key – value pair of the hash array. Syntax: %Certgrades = (
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 17
CIW Perl Fundamentals CIW Novell MS Cisco
=> "100", => "90", => "80", => "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. 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. Let’s look at the basic syntax:
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 18
CIW Perl Fundamentals 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. 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
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 19
CIW Perl Fundamentals
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 Perform a query to the DB The DO method is used to execute a query. Syntax: $dbn->do
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 20
CIW Perl Fundamentals 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
Special thanks to Robert J. Shimonski for contributing this Cramsession. Please visit his site at http://www.rsnetworks.net/
© 2001 All Rights Reserved – BrainBuzz.com 10/18/01 21