P. 1
11758242-PERL

11758242-PERL

|Views: 16|Likes:
Published by rakeshkallu

More info:

Published by: rakeshkallu on Nov 14, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

02/04/2012

pdf

text

original

1

PERL
Perl is a programming language developed by Larry Wall, especially designed for processing text. It stands for Practical Extraction and Report Language.

PERL Introduction:
Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. What You Should Already Know If you have basic knowledge of C or UNIX Shell then PERL is very easy to learn. If this is your first language to learn then you may take one to two week to be fluent in PERL What is PERL? • Perl is a stable, cross platform programming language. • Perl stands for Practical Extraction and Report Language. • It is used for mission critical projects in the public and private sectors. • Perl is Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL). • Perl was created by Larry Wall. • Perl 1.0 was released to usenet's alt.comp.sources in 1987 • PC Magazine named Perl a finalist for its 1998 Technical Excellence Award in the Development Tool category. • Perl is listed in the Oxford English Dictionary. Supported Operating Systems • Unix systems • Macintosh - (OS 7-9 and X) see The MacPerl Pages. • Windows - see ActiveState Tools Corp. • VMS • And many more... PERL Features • Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others. • Perls database integration interface (DBI) supports third-party databases including Oracle, Sybase, Postgres, MySQL and others. • Perl works with HTML, XML, and other mark-up languages. • Perl supports Unicode. • Perl is Y2K compliant. • Perl supports both procedural and object-oriented programming. • Perl interfaces with external C/C++ libraries through XS or SWIG. • Perl is extensible. There are over 500 third party modules available from the Comprehensive Perl Archive Network (CPAN). • The Perl interpreter can be embedded into other systems. PERL and the Web • Perl is the most popular web programming language due to its text manipulation capabilities and rapid development cycle. • Perl is widely known as " the duct-tape of the Internet". • Perl's CGI.pm module, part of Perl's standard distribution, makes handling HTML forms simple. • Perl can handle encrypted Web data, including e-commerce transactions. • Perl can be embedded into web servers to speed up processing by as much as 2000%. 1

2 • • mod_perl allows the Apache web server to embed a Perl interpreter. Perl's DBI package makes web-database integration easy.

Is Perl Compiled or Interpreted: Good question. The sort answer is interpreted, which means that your code can be run as is, without a compilation stage that creates a nonportable executebale program. Tradional compilers convert programs into machine language. When you run a Perl program, it's first compiled into a bytecode, which is then converted ( as the program runs) into machine instructions. So it is not quite the same as shells, or Tcl, which are "strictly" interpreted without an intermediate representation. Nor it is like most versions of C or C++, which are compiled directly into a machine dependent format. It is somewhere in between, along with Python and awk and Emacs .elc files.

PERL Syntax Overview:
A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a main() function or anything of that kind. Perl statements end in a semi-colon:
print "Hello, world"; # This is a comment

Comments start with a hash symbol and run to the end of the line Whitespace is irrelevant:
print "Hello, world"; # this would print with a linebreak in the middle print "Hello world";

... except inside quoted strings:

Double quotes or single quotes may be used around literal strings:
print "Hello, world"; print 'Hello, world';

However, only double quotes "interpolate" variables and special characters such as newlines (\n ):
print "Hello, $name\n"; print 'Hello, $name\n'; print 42; # works fine # prints $name\n literally

Numbers don't need quotes around them: You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence. Following two statements produce same result.
print("Hello, world\n"); print "Hello, world\n";

PERL File Extension:
A PERL script can be created inside of any normal simple-text editor program. There are several programs available for every type of platform. There are many programs designed for programmers available for download on the web. Regardless of the program you choose to use, a PERL file must be saved with a .pl (.PL) file extension in order to be recognized as a functioning PERL script. File names can contain numbers, symbols, and letters but must not contain a space. Use an underscore (_) in places of spaces.

First PERL Program:

2

3

Assuming you are already on Unix $ prompt. So now open a text file hello.pl using vi or vim editor and put the following lines inside your file.
#!/usr/bin/perl # This will print "Hello, Workd" on the screen print "Hello, world";

#!/usr/bin is the path where you have installed PERL

Execute PERL Script:
Before you execute your script be sure to CHMOD the script file and give execution priviledge, generally a setting of 0755 works perfectly. Now to run hello.pl Perl program from the Unix command line, issue the following command at your UNIX $ prompt:
$perl hello.pl

This will result in printing Hello World on your screen.

Perl Command Line Flags

Command line flags affect how Perl runs your program.
$perl -v RESULT : This is perl, version 5.001 ................

You can use -e option at command line which lets you execute Perl statements from the command line.
$perl -e 'print 4;' RESULT: 4 $perl -e "print 'Hello World!\n";' RESULT: Hello World!

PERL Variable Types:
Perl has three built in variable types • Scalar • Array • Hash

Scalar variable type:
A scalar represents a single value: at the bottom. A scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. There is no need to pre-declare your variable types. Scalar values can be used in various ways:
print $animal; print "The animal is $animal\n"; print "The square of $answer is ", $answer * $answer, "\n"; my $animal = "camel"; my $answer = 42; Here my is a keyword and has been explained in the same section

There are a number of "magic" scalars with names that look like punctuation or line noise. These special variables are used for all kinds of purposes and they wioll be discussed in Special Variables sections. The only one you need to know about for now is $_ which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs.
print; # prints contents of $_ by default

3

4

Array variable type:
An array represents a list of values:
my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23);

Arrays are zero-indexed but you can change this setting by changing default variable $[ or $ARRAY_BASE. Here's how you get at elements in an array:

print $animals[0]; # prints "camel" print $animals[1]; # prints "llama" The special variable $#array tells you the index of the last element of an array: print $mixed[$#mixed]; # last element, prints 1.23 You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context")

will give you the number of elements in the array:
if (@animals < 5) { ... } # Here @animals will return 3 The elements we're getting from the array start with a $ because we're getting just a single value

out of the array -- you ask for a scalar, you get a scalar. To get multiple values from an array:
@animals[0,1]; @animals[0..2];

# gives ("camel", "llama"); # gives ("camel", "llama", "owl");

@animals[1..$#animals]; # gives all except the first element

This is called an "array slice". You can do various useful things to lists:
my @sorted = sort @animals; my @backwards = reverse @numbers; # Here sort and reverse are Perl's built-in functions There are a couple of special arrays too, such as @ARGV (the command line arguments to your script) and @_ (the arguments passed to a subroutine). These are documented in next section

"Special Variables".

Hash variable type:
A hash represents a set of key/value pairs: Hash are type of arrays with the exception that hash index could be a number or string
my %fruit_color = ("apple", "red", "banana", "yellow"); You can use whitespace and the => operator to lay them out more nicely: my %fruit_color = ( apple => "red", banana => "yellow", );

To get a hash elements:

# gives "red" You can get at lists of keys and values with keys() and values() built-in my @fruits = keys %fruit_colors;

$fruit_color{"apple"};

functions.

4

there are also special hashes. More complex data types can be constructed using references. Just like special scalars and arrays. print "$result". For example there may become a time when you would like to print a dollar sign rather than use one to define a variable. Following line will print $ print "$variables->{'scalar'}->{'sigil'}\n" . { description => "key/value pairs". "owl"). To do this you must "escape" the character using a backslash (\). my $variables = { scalar => { description => "single item". 5 . }. though you can sort the keys and loop through them. So by storing a reference as the value of an array or hash element. The most well known of these is %ENV which contains environment variables. but when it is used in scalar context then it returnes number of elements contacined in it as following if (@animals < 5) { . }. "llama". which allow you to build lists and hashes within lists and hashes. } # Here @animals will return 3 my $number = 30. Variable Context: PERL treats same variable differently based on Context. Hashes have no particular internal order. Here output will be This is 30 Escaping Characters: In PERL we use the backslash (\) character to escape any type of character that might interfere with our code. sigil => '%'. hash => }.5 my @colors = values %fruit_colors. Here @animals is an array. sigil => '@'. you can easily create lists and hashes within lists and hashes. sigil => '$'. A reference is a scalar value and can refer to any other Perl data type. The following example shows a 2 level hash of hash structure using anonymous hash references. array => }. For example my @animals = ("camel"... $result = "This is " + "\$number". { description => "ordered list of items". Another examples: Here $number is an scalar and contained number in it but when it is called along with a string then oit becomes string in stead of number $result = "This is " + "$number".

The variables are scoped to the block (i. and $fOo are all separate variables as far as Perl is concerned. } print $a. Here output will be This is $number Case Sensitivity: Variable names are case sensitive. %get). # prints "bar" # prints "foo" # prints nothing. Scoped--magical built-ins like $/ must currently be localized with local instead. • Conditional (if/unless/elsif/else) • Loop (for/foreach/while/until/continue) • Subroutine • eval or do/require/use'd file If more than one value is listed. $foo. Variable Scoping: Throughout the previous section all the examples have used the following syntax: my $var = "value". and init it similar. Thus in the loop the scope of $line extends from its declaration throughout the rest of the loop construct (including the continue clause). and init it declare @oof lexical. print $a. too. $b has fallen out of scope Using my in combination with a use strict. # prints "foo" print $b. print $b. the final print $b would cause a compile-time error and prevent you from running the program. # # # # # declare $foo lexically local declare list of variables local declare $foo lexical. my my my my my $foo. with an attribute applied Lexical scopes of control structures are not bounded precisely by the braces that delimit their controlled blocks. However. you could just use: $var = "value". if ($some_condition) { my $b = "bar". The my is actually not required. in the example above. control expressions are part of that scope. Using strict is highly recommended. but not beyond it while (my $line = <>) { 6 . For instance. $FOO. the list must be placed in parentheses. a bunch of statements surrounded by curly-braces) in which they are defined. $x : Foo = $y. my creates lexically scoped variables instead. $foo = "flurp". Private Variables via my(): The my operator declares the listed variables to be lexically confined to the following but not limited to • Enclosing blocks. @oof = @bar.6 print $result". All listed elements must be legal lvalues. which is bad programming practice. (@wid. at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. the above usage will create global variables throughout your program. Have a look at the following example my $a = "foo".e.

This is known as dynamic scoping. die "'$answer' is neither 'yes' nor 'no'". eval. That means that all side-effects related to this magic still work with the localized value. Use the following line at the top of your program file to avoid any error. $exponent = "2 ** 8".39. # make list of variables local local $foo = "flurp". } Similarly. # make $foo dynamic. Consequently. use strict 'vars'. $slurp = . } continue { print $line. in the conditional the scope of $answer extends from its declaration through the rest of that conditional. } We encourage the use of lexically scoped variables. including any elsif and else clauses. } PERL Scalar Variable: Scalar variables are simple variables containing only one element--a string or a number. If you localize a special variable. A local just gives temporary values to global (meaning package) variables. local $foo. The bottom line here with scalar variables is that they contain only one single piece of data. if ((my $answer = <STDIN>) =~ /^yes$/i) { user_agrees(). What you see is what you get with scalar variables. This feature allows code like this to work : # Read the whole contents of FILE in $slurp { local $/ = undef. Numbers may contain exponents. or number. This will remind you to scope the variable using local or my keyword. Following are examples of Scalar Variables #!/usr/bin/perl $number = "5". letter. you'll be giving a new value to it. # make $foo dynamically local local (@wid. Temporary Values via local(): A local modifies its listed variables to be "local" to the enclosing block. $float = 12. which works more like C's auto declarations. but not beyond it. integers. } else { chomp $answer. or decimal values. it gets executed each time through a loop. and init it local @oof = @bar. } elsif ($answer =~ /^no$/i) { user_disagrees(). # We can also assign a scalar an empty (undefined) value: 7 . It does not create a local variable. # make @oof dynamic. and init it Because local is a run-time operator. Lexical scoping is done with my. %get). PERL!". but its magic won't go away. or do FILE --and to any subroutine called from within that block. it's more efficient to localize your variables outside the loop. $string = "Hello.7 $line = lc $line. Strings may contain any symbol.

\L. # Printing all the above values print "$number\n". $userdefined = q^Carrot is now our quote^. symbols.39 There is nothing: Scalar Strings: Strings are scalar as we mentioned previously. print "$exponent\n". There is no limit to the size of the string. x may be any character \Q Backslash (escape) all following non-alphanumeric characters. print "$string\n". Following are examples of how to define strings $single = 'This string is single quoted'. This will give following result 5 2 ** 8 Hello. print "$float\n". or \Q functions Here are few examples #!/usr/bin/perl 8 .8 $nothing = undef. print "There is nothing: $nothing\n". Character Description \L Transform all letters to lowercase \l Transform the next letter to lowercase \U Transform all letters to uppercase \u Transform the next letter to uppercase \n Begin on a new line \r Applys a carriage return \t Applys a tab to the string \f Applys a formfedd to the string \b Backspace \a Bell \e Escapes the next character \0nn Creates Octal formatted numbers \xnn Creates Hexideciamal formatted numbers \cX Control characters. any amount of characters. Some of these characters also work to format files created in PERL. $double = "This string is double quoted". When defining a string you may use single or double quotations. Think of these characters as miniature functions. you may also define them with the q subfunction. Formatting Strings w/ Formatting Characters: Strings can be formatted to your liking using formatting characters. PERL! 12. or words can make up your strings. \E Ends \U.

PERL assumed we wanted to replace every character after the 7th. PERL!".com!". substr($mystring. print "Before replacement : $mystring\n". #!/usr/bin/perl $mystring = "Hello. $small = "\uthis. "$PARTAILCAPS\n". with our new string.com! This.9 $newline = "Welcome to \ntutorialspoint. PERL" to "Hello. "$backslah\n". which means that we can index any of the characters in our strings with this number. "$small\n". the string you wish to index and the index number. substr($mystring. $backslah = "\Q'Hello World'\E!". PERL counts each character of the string beginning with 0 for the first character and continuing until it reaches the end of a string Two arguments must be sent with our substr() function. PERL!". print print print print print "$newline\n". This will give following result Welcome to tutorialspoint. 3. Each character of the string is automatically assigned a numeric value by PERL. PERL assumes that you are replacing every character from that index number to the end. #!/usr/bin/perl # Define a string to replace $mystring = "Hello. World!" quite easily. Here t will become capital !" $ALLCAPS = "\UThis completely will become capital!". 7) = "World!". If two arguments are sent. print "After replacement : $mystring\n". 6) = "World!". If we throw a third parameter in our function we can replace only a chunk of our string with a new string. This will give following result Before replacement : Hello. We can change the string "Hello. PERL! After replacement : Hello. World! Because we only specified one numeric parameter for the string. "$ALLCAPS\n". print "Before replacement : $mystring\n". $PARTIALCAPS = "\UThis half will/E become capital!". 9 . Here t will become capital ! THIS COMPLETELY WILL BECOME CAPITAL! THIS HALF WILL become capital! \'Hello World\'! Substr() and String Indexing: The substr() function allows for the temporary replacement of characters in a string.

But this is messy and is subject to the same basic laws regarding interpolation and quote usage. For example: 10 . octal. Numeric Scalars: Perl supports a number of a fairly basic methods for specifying a numeric literal in decimal: $num = 123. Another better way of printing multilines print <<EOF.10 print "After replacement : $mystring\n". # integer # floating point # scientific notation You can also specify literals in hexadecimal. This is a multiline string EOF V-Strings: V-strings can be a useful way of introducing version numbers and IP addresses into Perl.Perl converts the literal representation into a decimal internally.23e45.97. $num = 1. For example: $name = v77. # Octal $num = 0b0010_0000.105. This will give following result Before replacement : Hello. You can refer to each scalar within that list using a numerical index. you can use standard quotes: $string = 'This is a multiline string'.114. # Binary Note that the numbers are not stored internally using these bases. Array Creation: Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. They are any literal that begins with a v and is followed by one or more dot-separated elements.110.45. PERL Array Variable: An array is just a set of scalars. We could get around it using the q// or qq// operator with different delimiters.116. It's made up of a list of individual scalars that are stored within a single variable. and binary by specifying a preceding character to highlight the number types: $num = 0xff. $num = 123. # Hexadecimal $num = 0377. PERL! After replacement : HelWorld!RL! Multiline Strings: If you want to introduce multiline strings into your programs.

This means that you can use newlines within the specification: @days = qw/Monday Tuesday . For example: #!/usr/bin/perl @shortdays = qw/Mon Tue Wed Thu Fri Sat Sun/. rather than the beginning. # Outputs Sun $shortdays[-1]. of the array. This will print Tue Array indices start at zero. which returns a list of strings. In this example. $array[6] = 'Sunday'. Sunday/. Rather than typing out each element when counting to 100 for example. @array = qw/This is an array/. # Outputs Mon Sequential Number Arrays: PERL offers a shortcut for sequential numbers and letters.11 @array = (1. Extracting Individual Indices: When extracting individual elements from an array. you must prefix the variable with a dollar sign and then append the element index within square brackets after the name. # Also outputs Sun $shortdays[-7]..ve actually printed "Tue". You can also give a negative index. The second line uses the qw// operator. This means that print print print print $shortdays[0]. so in the preceding example we. 2.. this leads to a fourelement array. We can also populate an array by assigning each value individually: $array[0] = 'Monday'. the first element is 'this' and last (fourth) is 'array'. separating the delimited string by white space. # Outputs Mon $shortdays[6]. print $shortdays[1]..in which case you select the element from the end. we can do something like this: 11 . . 'Hello')..

3). but the array is 51 elements long.scalar @array. 1000).12 #!/usr/bin/perl @10 = (1 .. $array[50] = 4. "@1000".the returned value will be the number of elements in the array: @array = (1.. 10). z).3).. "@100". @abc = (a . and the difference between scalar @array and $#array.scalar @array. You can demonstrate this.2. print "Max Index: ". with a highest index of 50. $#array. not the number of valid elements. print "Size: ". @1000 = (100 . using this fragment: #!/uer/bin/perl @array = (1. 100. "@abc". print "Size: ". @100 = (1 . The value returned will always be the physical size of the array."\n". # # # # Prints Prints Prints Prints number number number number starting starting starting starting from from from from 1 1 1 a to to to to 10 100 1000 z Array Size: The size of an array can be determined using scalar context on the array .."\n".2. print print print print "@10"."\n". 12 . This will return Size: 51 Max Index: 50 There are only four elements in the array that contain information.

13 H e r e s c a l a r f u n c t i o n i s u s e d t o e n f o r c e s c a l a r 13 .

shift(@coins). range operator: @weekdays = @shortdays[0. print "\n". each separated by a comma.6. • shift() : removes the first element of an array. • pop(): removes the last element of an array. # Add one element at the beginning of the array unshift(@coins. Ranges also work in lists: @weekdays = @shortdays[0. Now this will produce following result First Statement : Quarter Dime Nickel Second Statement : Quarter Dime Nickel Penny Third Statement : Dollar Quarter Dime Nickel Penny Fourth Statement : Dollar Quarter Dime Nickel Fifth Statement : Quarter Dime Nickel Slicing Array Elements: You can also extract a "slice" from an array . either positive or negative. print "@coins". print "\n". print "\n". pop(@coins). #!/usr/bin/perl # Define an array @coins = ("Quarter". first the array name and second the name of the element to add. For speed. # Remove one element from the last of the array.2..14 Adding and Removing Elements in Array: Use the following functions to add/remove and elements: • push(): adds an element to the end of an array. # Remove one element from the beginning of the array.. When adding elements using push() or shift() you must specify two arguments. print "Fourth Statement : @coins". print "\n". print "Second Statement : @coins". "Dollar"). "Penny"). The specification for a slice must a list of valid indices. • unshift(): adds an element to the beginning of an array. print "First Statement : @coins".1.2. @weekdays = @shortdays[0. you can select more than one item from an array in order to produce another array."Dime". print "Third Statement : @coins". # Add one element at the end of the array push(@coins. you can also use the .4]. Removing an element with pop() or shift() only requires that you send the array as an argument."Nickel").3.4]..that is.7]. print "Fifth Statement : @coins". 14 .

splice(@nums. it is possible to transform a string into an array. Here '-' and '.Tom". you send PERL an array to splice.sequential_length. @names). @names = split('.5. $namelist = "Larry.". print $names[4].$astring). @array). @names = split('.25)..'. first the character of which to split and also the string variable. and then fill in the missing elements with new information. Here '-' and '.Tom". new elements) Essentially. $string1 = join(". print $array[3]. $namelist = "Larry.$namelist). # This will print Roses # This is a new line # This will print Michael Likewise. Here actual replacement begins after the 5th element. scalar string. Splice() requires a handful of arguments and the formula reads: splice(@array.Michael.Michael. Five elements are then replaced from 6-10 with the numbers 21-25 Transform Strings to Arrays: With the split function. This will produce following result 15 .'. we can use the join() function to rejoin the array elements and form one long.21. count through how many elements to replace.David.20). # Strings are now arrays. #!/usr/bin/perl @nums = (1. print "@nums".Ken.Roger. then direct it to the starting element.Ken. print $string2. 5. print $string1. #!/usr/bin/perl # Define Strings $astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens". print "\n". starting with the number 6.' works as delimeter @array = split('-'.$namelist). To do this simply define an array and set it equal to a split function.Roger.' works as delimeter @array = split('-'.first-element.$astring). # Strings are now arrays. The split function requires two arguments. $string2 = join("-". print "\n" .15 Replacing Array Elements: Replacing elements is possible with the splice() function.. #!/usr/bin/perl # Define Strings $astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens".David.

$[ will almost always be 0.6)). The Lists Lists are really a special type of array .3.16 Rain.On. Functions that return lists can also be embedded to produce a single..@even).2.3). This will produce following result Before sorting: pizza steak chicken burgers After sorting: burgers chicken pizza steak Please note that sorting is performed based on ASCII Numeric value of the words.Drops. The list can be "hand" generated using parentheses and the comma operator. It is recommended not to use any other indexing other than zero. print "After sorting: @foods\n". The embedded list just becomes part of the main list. or it can be the value returned by a function or variable when evaluated in list context: print join('. So the best option is to first transform every element of the array into lowercase letters and then perform the sort function.squares()).On.this also means that we can combine arrays together: @numbers = (@odd. The $[ Special Variable: $[ is a special variable.you can extract an element from an array by appending square brackets to the list and giving one or more indices: #!/usr/bin/perl 16 .And. This particular variable is a scalar containing the first index of all arrays. Selecting Elements from Lists: The list notation is identical to that for arrays . # Sort this array @foods = sort(@foods).Kittens Larry-David-Roger-Ken-Michael-Tom Sorting Arrays: The sort() function sorts each element of an array according to ASCII Numeric standards. Here.. print "Before sorting: @foods\n". because Perl arrays have zero-based indexing. final list: @numbers = (primes().' @array). #!/usr/bin/perl # Define an array @foods = qw(pizza steak chicken burgers). Merging Lists (or Arrays): Because a list is just a comma-separated sequence of values.essentially. the @array is being evaluated in list context because the join function is expecting a list.5. @array = (1.Whiskers. a list is a temporary construct that holds a series of values. you can combine lists together: @numbers = (1.Roses.(4. But if you set $[ to 1 then all your arrays will use on-based indexing.

One of the limitations of an array is that the information contained within it can be difficult to get to. you use a list. imagine that you have a list of people and their ages. print "Rikke is $ages{Rikke} years old\n". 'Sharon' => 35. In the first.3. you can use => as an alias for . This will produce follwoing result value of new list is 4 3 2 PERL Hash Variable: Hashes are an advanced form of array. This will produce following result Rikke is 29 years old Creation of Hash: Hashes are created in one of two ways.4. %ages = ('Martin' => 28. although without the requirement for a leading @ character: #!/usr/bin/perl @newlist = (5.2.2. 'Barney'.17 $one = (5. For example.1)[4]. For example. This will print following result 17 . print "value of new list is @newlist\n". 'Flintstone'. we can extract slices. %hash = ('Fred' .3.3]. but by a scalar key.). to indicate the key/value pairs: %hash = ('Fred' => 'Flintstone'. The hash solves this problem very neatly by allowing us to access that @ages array not by an index. 'Rikke' => 29. print "Value of \$one is $one\n" This will produce follwoing result Value of $one is 1 Similarly. 'Rubble'). Extracting Individual Elements: You can extract individual elements from a hash by specifying the key for the value that you want within braces: print $hash{Fred}.1)[1.4. 'Barney' => 'Rubble'). In the second case.. For example to use age of different people we can use thier names as key to define a hash. as the value. which is converted by taking individual pairs from the list: the first element of the pair is used as the key. and the second. For clarity. you assign a value to a named key on a one-byone basis: $ages{Martin} = 28.

values %ages). So to resolve this problem we have each function which will retun us key and value pair as given below #!/usr/bin/perl %ages = ('Martin' => 28."\n".18 Flintstone Extracting Slices: You can extract slices out of a hash just as you can extract slices from an array. print "The following are in the DB: ". $value) = each %ages) { print "$key is $ages{$key} years old\n". You do. 'Sharon' => 35. while (($key. '. 'Sharon' => 35. -Barney => 'Rubble'). -Barney} would return nothing. 'Rikke' => 29). } This will produce following result Rikke is 29 years old 29 is years old Martin is 28 years old 28 is years old Sharon is 35 years old 35 is years old The problem with this approach is that (%ages) returns a list of values. however. This will produce following result Flintstone Rubble Note: Using $hash{-Fred. foreach $key (%ages) { print "$key is $ages{$key} years old\n". 'Sharon' => 35. 'Rikke' => 29).@hash{-Fred. } This will produce following result Rikke is 29 years old Martin is 28 years old 18 . 35 These can be useful in loops when you want to print all of the contents of a hash: #!/usr/bin/perl %ages = ('Martin' => 28. 28. Extracting Keys and Values: You can get a list of all of the keys from a hash by using keys #!/usr/bin/perl %ages = ('Martin' => 28.join('. print join("\n". This will produce following result The following are in the DB: 29.-Barney}). need to use the @ prefix because the return value will be a list of corresponding values: #!/uer/bin/perl %hash = (-Fred => 'Flintstone'. 'Rikke' => 29).

you. as. foreach my $key (@sortorder) Hash Size: You get the size . For example: my @sortorder = sort keys %hash. print(join('.t exist. '.keys %hash). irrespective of what its value might be: #!/usr/bin/perl %ages = ('Martin' => 28.from a hash by using scalar context on either keys or values: #!/usr/bin/perl %ages = ('Martin' => 28. } This will produce following result I don't know the age of mohammad Sorting/Ordering Hashes: There is no way to simply guarantee that the order in which a list of keys. values. 19 . or key/value pairs will always be the same. for example: print(join('. This will produce following result Hash size: 3 Add & Remove Elements in Hashes: Adding a new key/value pair can be done with one line of code using simple assignment operator.ll normally get the undefined value. If you are accessing a hash a number of times and want to use the same order."\n"). You can get around this by using the exists function. 'Rikke' => 29).keys %hash).sort keys %hash). and if you have warnings switched on."\n". In fact. consider creating a single array to hold the sorted sequence.that is. 'Sharon' => 35. and then use the array (which will remain in sorted order) to iterate over the hash."\n"). print "Hash size: ". then you. '.19 Sharon is 35 years old Checking for Existence: If you try to access a key/value pair from a hash that doesn. 'Rikke' => 29).ll get a warning generated at run time. If you want to guarantee the order. } else { print "I don't know the age of mohammad\n". '. if (exists($ages{"mohammad"})) { print "mohammad if $ages{$name} years old\n". the number of elements .scalar keys %ages. 'Sharon' => 35. But to remove an element from the hash you need to use delete function. it's best not even to rely on the order between two sequential evaluations: #!/usr/bin/perl print(join('. use sort."\n"). which returns true if the named key exists.

• The default iterator variable in a foreach loop if no other variable is supplied. That's because in each iteration of the loop. Here are the places where Perl will assume $_ even if you don't specify it: • Various unary functions. # Remove one element from the hash delete( $age{'Sharon'} ). The second time around. ). 20 . and tr/// when used without an =~ operator. "doc" is printed. the current string is placed in $_. and is used by default by print. PERL Special Variables: Some variables have a predefined and special meaning in Perl.e. Most of the special variables have an english like long name eg. The most commonly used special variable is $_.'dickory'. or %). and the third time. But if you are going to use english like names then you would have to put one line "use English. • The implicit iterator variable in the grep and map functions. which contains the default input and patternsearching string. } This will produce following result hickory dickory doc The first time the loop is executed. which defaults to STDIN. # Add one more element in the hash $age{'John'} = 40. including functions like ord and int. Note that outside of a while test. 'Rikke' => 29). • The pattern-matching operations m//. Operating System Error variable $! can be written as $OS_ERROR. • Various list functions like print and unlink. 'Sharon' => 35. This guides the interter to pickup exact meaning of the variable.. They are the variables that use punctuation characters after the usual variable indicator ($. such as $_ ( explained below ).20 #!/usr/bin/perl %ages = ('Martin' => 28. @. in the following lines: #!/usr/bin/perl foreach ('hickory'. -d) except for -t. "dickory" is printed. "hickory" is printed. as well as the all file tests (-f. print "\n". • The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.'doc') { print. this will not happen. s///." at the top of your program file. For example.

. • Filehandle Special Variables. BLOCK elsif (EXPR) BLOCK . as in: print "Happy Birthday!\n" if ($date == $today). The third format allows for exceptions. The second format is the more familiar conditional statement that you may have come across in other languages: if ($date == $today) { print "Happy Birthday!\n". • Global Special Filehandles.. • Regular Expression Special Variables. } This produces the same result as the previous example. since it can be used at the end of another statement without requiring a block.21 Special variable types Based on the usage and nature of special variables we can categories them in the following categories • Global Scalar Special Variables. • Global Special Constants. otherwise (else). • Global Array Special Variables. PERL Conditional Statements: The conditional statements are if and unless. then the first block is executed. the message will only be printed if the expression evaluates to a true value. the second block is executed: 21 . else BLOCK if (EXPR) The first format is classed as a simple statement. • Global Hash Special Variables. There are five different formats for the if statement: if (EXPR) if (EXPR) if (EXPR) if (EXPR) if (EXPR) STATEMENT BLOCK BLOCK else BLOCK BLOCK elsif (EXPR) BLOCK . If the expression evaluates to true.. and they allow you to control the execution of your script.. In this instance.

} elsif ($date == $christmas) { print "Happy Christmas!\n". } The fourth form allows for additional tests if the first expression does not return true. } The unless statement automatically implies the logical opposite of if. This means that the statement 22 . }else { print "Happy Unbirthday!\n". The elsif can be repeated an infinite number of times to test as many different alternatives as are required: if ($date == $today) { print "Happy Birthday!\n". so unless the EXPR is true. } The fifth form allows for both additional tests and a final exception if all the other tests fail: if ($date == $today) { print "Happy Birthday!\n". } else { print "Happy Unbirthday!\n". } elsif ($date == $christmas) { print "Happy Christmas!\n". execute the block.22 if ($date == $today) { print "Happy Birthday!\n".

. } else { print "Happy Birthday!\n". while 2.. For example. the following is a less elegant solution to the preceding if. It is synonymous with the if. The format for the operator is: (expression) ? (statement if true) : (statement if false) For example.23 print "Happy Unbirthday!\n" unless ($date == $today). for 3. the execution of the loop continues until the evaluation of the supplied expression changes. foreach In each case. 23 . • In the case of a while loop execution continues while the expression evaluates to true. we can emulate the previous example as follows: ($date == $today) ? print "Happy B.else conditional statement but is shorter and more compact. example: unless ($date != $today) { print "Happy Unbirthday!\n".the conditional operator. is equivalent to print "Happy Unbirthday!\n" if ($date != $today).else. } The final conditional statement is actually an operator. PERL Loops: Perl supports four main loop types: 1.Day!\n" : print "Happy Day!\n". Although it achieves the same result.. until 4..

For example: Do { $calc += ($fact*$ivalue). To create a loop that executes statements first. while Loops: The while loop has three forms: while EXPRLABEL while (EXPR) BLOCKLABEL while (EXPR) BLOCK continue BLOCK In first form. the following line increases the value of $linecount as long as we continue to read lines from a given file: $linecount++ while (). and then the statement to which it applies is evaluated. irrespective of how the current iteration terminated. } The continue block is executed immediately after the main block and is primarily used as a method for executing a given statement (or statements) for each iteration. In this case. The second two forms of the while loop repeatedly execute the code block as long as the result from the conditional expression is true. you could rewrite the preceding example as: while($calc < 100) { $calc += ($fact*$ivalue). They continue until the end of the supplied list is reached. The list forms of the for and foreach loop are special cases.24 • • The until loop executes while the loop expression is false and only stops when the expression evaluates to a true value. and then tests an expression. } while $calc <100. For example. you need to combine while with a preceding do {} statement. the expression is evaluated first. It is somehow equivalent to for loop 24 . the following line increases the value of $linecount as long as we continue to read lines from a given file: For example. For example. and the conditional expression is only evaluated at the end of each loop iteration. the code block is executed first.

25
{ my $i = 0; while ($i <100) { ... } continue { $i++; }

}

This is equivalent to for (my $i = 0; $i < 100; $i++) { ... }

for Loops:
A for loop is basically a while loop with an additional expression used to reevaluate the original conditional expression. The basic format is:
LABEL for (EXPR; EXPR; EXPR) BLOCK

The first EXPR is the initialization - the value of the variables before the loop starts iterating. The second is the expression to be executed for each iteration of the loop as a test. The third expression is executed for each iteration and should be a modifier for the loop variables. Thus, you can write a loop to iterate 100 times like this:
for ($i=0;$i<100;$i++) { ... }

You can place multiple variables into the expressions using the standard list operator (the comma):
for ($i=0, $j=0;$i<100;$i++,$j++)

You can create an infinite loop like this:

25

26
for(;;) { ... }

until Loops:
The inverse of the while loop is the until loop, which evaluates the conditional expression and reiterates over the loop only when the expression returns false. Once the expression returns true, the loop ends. In the case of a do.until loop, the conditional expression is only evaluated at the end of the code block. In an until (EXPR) BLOCK loop, the expression is evaluated before the block executes. Using an until loop, you could rewrite the previous example as:
Do { $calc += ($fact*$ivalue); } until $calc >= 100; This is equivalent to do {

$calc += ($fact*$ivalue); } while $calc <100;

foreach Loops:
The last loop type is the foreach loop, which has a format like this:
LABEL foreach VAR (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK

Using a for loop, you can iterate through the list using:
for ($index=0;$index<=@months;$index++) { print "$months[$index]\n"; }

This is messy, because you.re manually selecting the individual elements from the array and using an additional variable, $index, to extract the information. Using a foreach loop, you can simplify the process:

26

27
foreach (@months) { print "$_\n"; }

The foreach loop can even be used to iterate through a hash, providing you return the list of values or keys from the hash as the list:
foreach $key (keys %monthstonum) { print "Month $monthstonum{$key} is $key\n"; }

Labled Loops:
Labels can be applied to any block, but they make the most sense on loops. By giving your loop a name, you allow the loop control keywords to specify which loop their operation should be applied to. The format for a labeled loop is:
LABEL: loop (EXPR) BLOCK ...

For example, to label a for loop:
ITERATE: for (my $i=1; $i<100; $i++) { print "Count: $i\n"; }

Loop Control - next, last and redo:
There are three loop control keywords: next, last, and redo. The next keyword skips the remainder of the code block, forcing the loop to proceed to the next value in the loop. For example:
while (<DATA>) { next if /^#/; }

Above code would skip lines from the file if they started with a hash symbol. If there is a continue block, it is executed before execution proceeds to the next iteration of the loop. The last keyword ends the loop entirely, skipping the remaining statements in the code block, as well as dropping out of the loop. The last keyword is therefore identical to the break keyword in C
27

28

and Shellscript. For example:
while () { last if ($found); }

Would exit the loop if the value of $found was true, whether the end of the file had actually been reached or not. The continue block is not executed. The redo keyword reexecutes the code block without reevaluating the conditional statement for the loop. This skips the remainder of the code block and also the continue block before the main code block is reexecuted. For example, the following code would read the next line from a file if the current line terminates with a backslash:
while(<DATA>) { if (s#\\$#) { $_ .= <DATA>; redo; } }

Here is an example showing how labels are used in inner and outer loops
OUTER: while(<DATA>) { chomp; @linearray=split; foreach $word (@linearray) { next OUTER if ($word =~ /next/i) } }

goto Statement:
There are three basic forms: goto LABEL, goto EXPR, and goto &NAME. In each case, execution is moved from the current location to the destination. In the case of goto LABEL, execution stops at the current point and resumes at the point of the label specified. The goto &NAME statement is more complex. It allows you to replace the currently executing subroutine with a call to the specified subroutine instead.

28

or and not aren't just in the above table as descriptions of the operators -they're also supported as operators in their own right. Miscellaneous Operators: 29 . but have different precedence to && and friend.29 PERL Built-in Operators: There are many Perl operators but here are a few of the most common ones: Arithmetic Operators: + * / addition subtraction multiplication division Numeric Comparison Operators: == != < > <= >= equality inequality less than greater than less than or equal greater than or equal String Comparison Operators: eq ne lt gt le ge equality inequality less than greater than less than or equal greater than or equal (Why do we have separate numeric and string comparisons? Because we don't have special variable types. They're more readable than the C-style operators. Boolean Logic Operators: && || ! and or not (and . and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).

= "\n". ?: = += -= *= etc. even where C's precedence is slightly screwy..) With very few exceptions. . listed from highest precedence to lowest. these all operate on scalar values only. => list operators (rightward) not and or xor 30 . << >> named unary operators < > <= >= lt gt le ge == != <=> eq ne cmp & | ^ && || . . Operators borrowed from C keep the same precedence relationship with each other.1 # same as $a = $a . x .30 = . not array values. $a -= 1. left left nonassoc right right left left left left nonassoc nonassoc nonassoc left left left left nonassoc right right left nonassoc right left left terms and list operators (leftward) -> ++ -** ! ~ \ and unary + and =~ !~ * / % x + . "\n". # same as $a = $a + 1 # same as $a = $a .. assignment string concatenation string multiplication range operator (creates a list of numbers) Many operators can be combined with a = as follows: $a += 1... $a .. (This makes learning Perl easier for C folks. Operator Precedence and Associativity: Perl operators have the following associativity and precedence.

This example actually truncates (empties) the file before opening it for writing. STDOUT. To truncate the file first: open DATA. You can open a file in append mode. so you can read from and update any file or device associated with a filehandle.txt in read-only mode.">>file. while(<DATA>) { print "$_". In this mode writing point will be set to the end of the file open(DATA. MODE Here FILEHANDLE is the file handle returned by open function and EXPR is the expression having file name and mode of opening the file. However. Here less than > signe indicates that file has to be opend in writing mode open(DATA.txt" or die "Couldn't open file file. A filehandle is a named internal Perl structure that associates a physical file with a name.txt"). ">file. Following is the syntax to open file. $!". For example.txt").txt. Here DATA is the file handle which will be used to read the file. which may not be the desired effect. FILENAME. to open a file for updating without truncating it: open(DATA. "+<file. Here is the example which will open a file and will print its content over the screen. and STDERR.txt"). "<file.31 PERL Files & I/O: The basics of handling files are simple: you associate a filehandle with an external entity (usually a file) and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle. All filehandles are capable of read/write access. Three basic file handles are . MODE. 31 .txt.txt in writing mode. FILENAME. $!". open FILEHANDLE. Here less than < signe indicates that file has to be opend in read-only mode open(DATA. EXPR open FILEHANDLE sysopen FILEHANDLE. #!/usr/bin/perl open(DATA. "+>file. } Open Function: Following is the syntax to open file. If you want to open a file for reading and writing. you can put a plus sign before the > or < characters. you can specify the mode in which the filehandle is opened.STDIN. PERMS sysopen FILEHANDLE. when you associate a filehandle.txt") || die "Couldn't open file file.txt"). "<file. Opening and Closing Files: There are following two functions with multiple forms which can be used to open any new or existing file in Perl.

It returns true only if it could successfully flush the buffers and close the file. placing the file pointer at the end. Reading and Writing Filehandles: Once you have an open filehandle. Writes. using the parameters supplied to it as the parameters for the system function: For example. and Creates Reads and Writes Reads. Following is the table which gives possible values of different modes Entities < or r > or w >> or a +< or r+ +> or w+ +>> or a+ Definition Read Only Access Creates. $!". or to truncate the file before updating: sysopen(DATA. you need to be able to read and write information. The PERMS argument specifies the file permissions for the file specified if it has to be created. "file. you use the close function. Appends. and Truncates Reads. O_RDWR).txt") || die "Couldn't open file file. However.to open file in write only mode and O_RDONLY . "file. Appends. This flushes the filehandle's buffers and closes the system's file descriptor. then it closes the currently selected filehandle. You can use O_CREAT to create a new file and O_WRONLY. except that it uses the system open() function.t read from it unless you also place a plus sign in front of it: open(DATA.to open file in read only mode. emulating the +<filename format from open: sysopen(DATA. 32 .txt". Writes.32 A double >> opens the file for appending.txt"."+>>file. to open a file for updating. so that you can immediately start appending information. close(DATA) || die "Couldn't close file properly". Creates. close FILEHANDLE close If no FILEHANDLE is specified. Writes. you can.txt. There are a number of different ways of reading and writing data into the file. and therefore disassociate the filehandle from the corresponding file. and Creates Sysopen Function: The sysopen function is similar to the main open function. By default it takes 0x666 Following is the table which gives possible values of MODE Value O_RDWR O_RDONLY O_WRONLY O_CREAT O_APPEND O_TRUNC O_EXCL exists O_NONBLOCK Definition Read and Write Read Only Write Only Create the file Append the file Truncate the file Stops if file already Non-Blocking usability Close Function: To close a filehandle. O_RDWR|O_TRUNC ). and Truncates Writes.

read FILEHANDLE.txt") or die "Can't open data". and the data is placed at the start of SCALAR if no OFFSET is specified.txt and read it line by line and generate another copy file2. When you use the <FILEHANDLE> operator in a list context. @lines = <DATA>.txt"). read Function: The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file. zero at end of file. SCALAR. In a scalar context it returns a single line from the filehandle. For example.txt #!/usr/bin/perl # Open file to read open(DATA1.33 The <FILEHANDL> Operator The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. print "Hello $name\n". "<file1. $name = <STDIN>. Otherwise data is placed after OFFSET bytes in SCALAR. or undef if there was an error. print Function: For all the different methods used for reading information from filehandles."<import. then undef is returned instead. SCALAR. OFFSET read FILEHANDLE. print FILEHANDLE LIST print LIST print The print function prints the evaluated value of LIST to FILEHANDLE. For example: #!/usr/bin/perl print "What is your name?\n". or the filehandle is at end of file. For example: print "Hello World!\n". LENGTH The length of the data read is defined by LENGTH. to import all the lines from a file into an array: #!/usr/bin/perl open(DATA. getc Function: The getc function returns a single character from the specified FILEHANDLE. or STDIN if none is specified: getc FILEHANDLE getc If there was an error. close(DATA). it returns a list of lines from the specified filehandle. or to the current output filehandle (STDOUT by default). LENGTH. Copying Files: Here is the example which opens an existing file file1. the main function for writing information back is the print function. # Open new file to write 33 . The function returns the number of bytes read on success.

or the current default selected filehandle if none is specified.txt" ). #!/usr/bin/perl unlink ("/usr/test/file1. the line sets the file pointer to the 256th byte in the file. and you have the same ability to position relative to three different points: the start. This function rename takes two arguments and it just rename existing file Deleting an exiting file: Here is an example which shows how to delete a file file1. while(<DATA1>) { print DATA2 $_. You do this by specifying a value for WHENCE. "/usr/test/file2. and the current position.34 open(DATA2. ">file2.txt to file2. For example.txt". # Copy data from one file to another. Assuming file is available in /usr/test directory. seek DATA.txt using unlink function.txt"). seek Function The seek function positions the file pointer to the specified number of bytes within a file: seek FILEHANDLE. close( DATA2 ). Getting File Information: You can test certain features very quickly within Perl using a series of test operators known collectively as -X tests. tell Function The first requirement is to find your position within a file. to perform a quick test of the various permissions on a file.txt. Locating Your Position Within a File: You can use to tell function to know the current position of a file and seek function to point a particular position inside the file. which you do using the tell function: tell FILEHANDLE tell This returns the position of the file pointer. 0. #!/usr/bin/perl rename ("/usr/test/file1. For example. in bytes. Renaming a file: Here is an example which shows how we can rename a file file1. within FILEHANDLE if specified. POSITION. the end. Zero sets the positioning relative to the start of the file. } close( DATA1 ). WHENCE The function uses the fseek system function.txt"). you might use a script like this: #/usr/bin/perl 34 . 256.

POS closedir DIRHANDLE # # # # # # To open a directory To read a directory Positioning pointer to the begining Returns current position of the dir Pointing pointer to POS inside dir Closing a directory. (($size = -s _)) ? "$size bytes" : 'empty'. push @description. -O Is the file owned by the real user ID? -R Is the file readable by the real user ID or real group? -S Is the file a socket? -T Is it a text file? -W Is the file writable by the real user ID or real group? -X Is the file executable by the real user ID or real group? -b Is it a block special file? -c Is it a character special file? -d Is the file a directory? -e Does the file exist? -f Is it a plain file? -g Does the file have the setgid bit set? -k Does the file have the sticky bit set? -l Is the file a symbolic link? -o Is the file owned by the effective user ID? -p Is the file a named pipe? -r Is the file readable by the effective user or group ID? -s Returns the size of the file."\n". Here is an example which opens a directory and list out all the files available inside this directory. push @description.@description). push @description. print "$file is ". 'a block special file' if (-b _). if (-e $file) { push @description.35 my (@description. push @description. } Here is the list of features which you can check for a file Operator Description -A Age of file (at script startup) in days since modification. 'a socket' if (-S _). opendir DIRHANDLE. 'a character special file' if (-c _).$size). -B Is it a binary file? -C Age of file (at script startup) in days since modification. push @description. -M Age of file (at script startup) in days since modification. 'binary' if (-B _). zero size = empty file. push @description. push @description. 'a text file' if (-T _). -t Is the filehandle opened by a TTY (terminal)? -u Does the file have the setuid bit set? -w Is the file writable by the effective user or group ID? -x Is the file executable by the effective user or group ID? -z Is the file size zero? Working with Directories: Following are the standard functions used to play with directories. '. 35 . EXPR readdir DIRHANDLE rewinddir DIRHANDLE telldir DIRHANDLE seekdir DIRHANDLE. 'a directory' if (-d _). 'executable' if (-x _). join('.

but for all other delimiters you 36 . m{}. to match the character sequence "foo" against the scalar $bar.s/// • Transliterate Regular Expression . $!".m// • Substitute Regular Expression . The Match Operator: The match operator. is used to match a string or statement to a regular expression. You can omit the m from m// if the delimiters are forward slashes. } closedir DIR. } closedir DIR. use the rmdir function: To change the directory you can use chdir function. you might use #!/usr/bin/perl opendir(DIR.36 #!/usr/bin/perl opendir (DIR. Another example to print the list of C source code files. and m>< are all valid.you can use any combination of naturally matching characters to act as delimiters for the expression. You can make a new directory using the mkdir function: To remove a directory. For example.*\. '. $!". There are three regular expression operators within Perl • Match Regular Expression . m().c$/.') or die "Couldn't open directory. The basic method for applying a regular expression is to use the pattern binding operators =~ and ! ~.supporting programs. m//.readdir(DIR))) { print "$_\n". The first operator is a test and assignment operator. grep. foreach (sort grep(/^. and awk. such as sed. '. while ($file = readdir DIR) { print "$file\n". For example.') or die "Couldn't open directory. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression. If you are comfortable with any other delimiter then you can use in place of forward slash. you might use a statement like this: if ($bar =~ /foo/) The m// actually works in the same fashion as the q// operator series.tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. PERL Regular Expressions: A regular expression is a string of characters that define the pattern or patterns you are viewing.

that is the expression on the left of =~ or !~ and the match operator. the match returns the contents of any grouped expressions. Here is the complete list of modifiers Modifier Description i Makes the match case insensitive m Specifies that if the string has newline or carriage return characters. Therefore the statement: $true = ($foo =~ m/foo/). you can use this to get the first and last elements within a list: 37 . Will set $true to 1 if $foo matches the regex. In a list context. For example.37 must use the m prefix. For example. to match a newline character x Allows you to use white space in the expression for clarity g Globally finds all matches cg Allows the search to continue even after a global match fails Matchi ng Only Once There is also a simpler version of the match operator . minutes. $minutes. The /i modifier will make the match case insensitive. instead of a string boundary o Evaluates the expression only once s Allows use of . and seconds from a time string. when extracting the hours. $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/). Note that the entire match expression. we can use: my ($hours. returns true (in a scalar context) if the expression matches.the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset. Match Operator Modifiers: The match operator supports its own set of modifiers. The /g modifier allows for global matching. the ^ and $ operators will now match against a newline boundary. or 0 if the match fails.

print "Final Result is $string\n". The basic form of the operator is: s/PATTERN/REPLACEMENT/. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. This will produce following result The dog sat on the mat Substitution Operator Modifiers: Here is the list of all modifiers used with substitution operator 38 . Last: $last\n". s///.*)?. we can replace all occurrences of . This will produce following result First: food.*)/. The PATTERN is the regular expression for the text that we are looking for. } print "First: $first. using $string =~ s/dog/cat/. Last: footbrdige The Substitution Operator: The substitution operator. $string =~ s/cat/dog/.38 #!/usr/bin/perl @list = qw/food foosball subeo footnote terfoot canic footbrdige/. For example. $last = $1 if /(foo. Another example: #/user/bin/perl $string = 'The cat sat on the mat'.cat. foreach (@list) { $first = $1 if ?(foo.dog. is really just an extension of the match operator that allows you to replace the text matched with some new text. with .

39 .39 Modifier Description i Makes the match case insensitive m Specifies that if the string has newline or carriage return characters. to the principles of substitution. but not identical. Standard Perl ranges can also be used. you might use following syntax in place of the uc function. print "$string\n". using the "The cat sat on the mat. to match a newline character x Allows you to use white space in the expression for clarity g Replaces all occurrences of the found expression with the replacement text e Evaluates the replacement as if it were a Perl statement." string we have been using in this chapter: #/user/bin/perl $string = 'The cat sat on the mat'. allowing you to specify ranges of characters either by letter or numerical value. but unlike substitution. This will produce following result The cot sot on the mot. the ^ and $ operators will now match against a newline boundary. instead of a string boundary o Evaluates the expression only once s Allows use of . The translation operators are: tr/SEARCHLIST/REPLACEMENTLIST/cds y/SEARCHLIST/REPLACEMENTLIST/cds The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example. $string =~ tr/a/o/. and uses its return value as the replacement text Translation : Translation is similar. To change the case of the string. translation (or transliteration) does not use regular expressions for its search on replacement values.

$string = 'food'.40 $string =~ tr/a-z/A-Z/. print "$string\n". you can match on just about anything you could dream of by using more complex regular expressions. s Squash duplicate replaced characters. This will produce following result b b b. The last modifier. For example: #!/usr/bin/perl $string = 'the cat sat on the mat. $string =~ tr/a-z/a-z/s. This will produce following result Fod More complex regular expressions: You don't just have to match on fixed strings. d Delete found but unreplaced characters. removes the duplicate sequences of characters that were replaced. In fact. Translation Operator Modifiers: Following is the list of operators related to translation Modifier Description c Complement SEARCHLIST. so: #!/usr/bin/perl $string = 'food'. The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. print $string.'. $string =~ tr/a-z/b/d. Here's a quick cheat sheet: 40 . /s.

0-9. Character * + ? {3} {3. one of the metacharacters listed above. newline) non-whitespace character a digit (0-9) a non-digit a word character (a-z. each followed by a whitespace # character (eg "3 4 5 ") /(\d\s){3}/ # matches a string in which every # odd-numbered letter is a (eg "abacadaf") /(a. Here are some brief examples # nothing in the string (start and end are adjacent) /^$/ # a three digits.} Description zero or more of the previous thing one or more of the previous thing zero or one of the previous thing matches exactly 3 of the previous thing matches between 3 and 6 of the previous thing matches 3 or more of the previous thing The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of the string.41 Character . A-Z. _) a non-word character matches a single character in the given set matches a single character outside the given set matches any of the alternatives specified Quantifiers can be used to specify how many of the previous thing you want to match on. where "thing" means either a literal character. \s \S \d \D \w \W [aeiou] [^aeiou] (foo|bar|baz) Description a single character a whitespace character (space. or a group of characters or metacharacters in parentheses. tab.)+/ # string starts with one or more digits /^\d+/ # string that ends with one or more digits /\d+$/ Lets have alook at another example 41 .6} {3.

there is no difference between except. This will produce following result First word: Cats Line starts: Cats When Matching Boundaries: The \b matches at any word boundary."Line starts: @lines\n". @lines = $string =~ /^(.*?) /). Searching for two people. It specifies alternate matches within a regular expression or group. and \W the opposite. you might use this: if ($string =~ /cat|dog/) You can group individual elements of an expression together in order to support complex matches. like this: if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/)) This could be written as follows if ($string =~ /(Martin|Sharon) Brown/) Grouping Matching: From a regular-expression point of view. For example: /\bcat\b/ /\Bcat\B/ /\bcat\B/ /\Bcat\b/ # # # # Matches Matches Matches Matches 'the cat sat' but not 'cat on the mat' 'verification' but not 'the cat on the mat' 'catatonic' but not 'polecat' 'polecat' but not 'catatonic' Selecting Alternatives: The | character is just like the standard or bitwise OR within Perl. that the 42 . print "First word: $start\n". to match "cat" or "dog" in an expression. this normally means the termination of a word.*?) /gm. The \B assertion matches any position that is not a word boundary. ($start) = ($string =~ /\A(. Because \w includes the characters for a word.s names could be achieved with two separate tests. For example.42 #!/usr/bin/perl $string = "Cats go Catatonic\nWhen given Catnip". as defined by the difference between the \w class and the \ W class. perhaps.

$string =~ /(\S+)\s+(\S+)/. When groups are used in substitution expressions. where x is the number of the group within the regular expression. in the following fragment we have pulled out the hours. print "$date". my ($hours. $minutes. $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/). minutes. This will produce following result 1999/03/26 Using the \G Assertion: The \G assertion allows you to continue searching from the point where the last match occurred. in the following code we have used \G so that we can search to the correct position and then extract some information. $date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#. We could therefore rewrite the preceding example as follows: $time =~ m/(\d+):(\d+):(\d+)/. and $string =~ /\S+\s+\S+/. $seconds) = ($1. As well as this direct method. the benefit of grouping is that it allows us to extract a sequence from a regular expression. and seconds from a string. $3). my ($hours.43 former is slightly clearer. For example. without having to create a more complex. For example. $2. single regular expression: 43 . $minutes. matched groups are also available within the special $x variables. Thus. Groupings are returned as a list in the order in which they appear in the original. we could reformat a date string using this: #!/usr/bin/perl $date = '03/26/1999'. the $x syntax can be used in the replacement text. However.

print "Time: $time. the print function takes variables and static text and prints the values on the screen. which contains everything after the matched string. 44 . This code prints the following when executed: Before: The Matched: foo After: d is in the salad bar PERL Subrountines: The two terms function and subroutine are used interchangeably in Perl. A function is a named code block that is generally intended to process specified input values into an output value. Perl provides for user-defined subroutines. print "Before: $`\n". =~ /.44 #!/usr/bin/perl $string = "The time is: 12:31:02 on 4/12/00". $`. print "After: $'\n". • Like many languages. Date: 4/12/00 The \G assertion is actually just the metasymbol equivalent of the pos function. although this is not always the case. • These may be located anywhere in the main program. which contains everything before the matched string. which contains whatever the last grouping match matched. and $'. The following code demonstrates the result: #!/usr/bin/perl $string = "The food is in the salad bar". which contains the entire matched string. = ($string =~ m{\G(\d+/\d+/\d+)}). print "Matched: $&\n". $string ($time) $string ($date) =~ /:\s+/g. This will produce following result Time: 12:31:02. and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine: Regular Expression Variables: Regular expression variables include $. $&. Date: $date\n". so between regular expression calls you can continue to use pos.+\s+/g. $string =~ m/foo/. For example. = ($string =~ /\G(\d+:\d+:\d+)/).

this simple function adds two numbers and prints the result: 45 . you use one of the following forms: • • • • • sub sub sub sub NAME NAME PROTO NAME ATTRS NAME PROTO ATTRS where NAME is the name of the subroutine you are creating. If the last statement is a loop control structure like a foreach or a while . its value is returned. For example. then you need to include the BLOCK that defines its operation: sub sub sub sub NAME NAME NAME NAME BLOCK PROTO BLOCK ATTRS BLOCK PROTO ATTRS BLOCK You can also create anonymous subroutines . PROTO is the prototype for the arguments the subroutine should expect when called. the returned value is unspecified. Any arguments passed in show up in the array @_. and ATTRS is a list of attributes that the subroutine exhibits. If no return is found and if the last statement is an expression. like variables. • Subroutines can return Scalar. If you want to declare and define a function.45 Loaded in from other files via the do. Array or Hash.subroutines without a name by omitting the NAME component: sub sub sub sub BLOCK PROTO BLOCK ATTRS BLOCK PROTO ATTRS BLOCK To call a function you would use one of the following forms: NAME NAME LIST NAME (LIST) &NAME To give a quick example of a simple subroutine: sub message { print "Hello!\n". the second argument is $_[1]. or use keywords. and so on. A return statement may be used to exit a subroutine. require. can be declared (without defining what they do) or declared and defined. Subroutines. } Function Arguments: The first argument you pass to the subroutine is available within the function as $_[0]. To simply declare a subroutine.

} To call the subroutine and get a result: add(1.: 46 . Return Values from a Function: The return value of any block. my $numberb = shift. The preceding subroutine is fairly simple. } The shift function is one of the . The shift function returns (and removes) the first element of an array. } The effect is exactly the same as we have shown earlier but we have just obtained the arguments in a different way. my $result = $numbera + $numberb. $numberb) = @_. including those used in subroutines.e the return value here is the result of the calculation. operands supported by Perl. For example: sub add { my $numbera = shift.2). is taken as the value of the last evaluated expression. print "The result was: $result\n". print "The result was: $result\n". but what if you wanted to have named arguments? The simple answer is to assign the values of @_ to a list of variables: sub add { ($numbera.46 sub add { $result = $_[0] + $_[1]. For exampl. print "The result was: $result\n".stack. $result = $numbera + $numberb.

the following two calls to the getpwent function return a list or a scalar. Here's another example. according to what was used in the assignation: $name = getpwent().47 sub myfunc { $_[0]+$_[1]. This allows you to use a single function that returns different values based on what the user is expecting to receive. $quota. In the second case. $dir. In the first case. the user expects a scalar value to be returned by the function. Thu Nov 30 15:21:33 2000. $shell) = getpwent(). } else { return 0. ($name. } } When called. again because a list of scalars has been specified for the information to be inserted into. If you don't specify a value then the return value is undef. because that is what the return value is being assigned to. %gcos. $comment. that shows the flexibility: my $timestr = localtime(time). the value of $timestr is now a string made up of the current date and time. the user expects an array as the return value. again from the built-in Perl functions. Conversely: 47 . A Function Call Context: The context of a subroutine or statement is defined as the type of return value that is expected. $uid. $gid. For example. In this example. for example. $passwd. } You can also explicitly return a value using the return keyword: sub myfunc { if (@_) { return $_[0]+$_[1]. return immediately terminates the current subroutine and returns the value to the caller.

you have to declare the subroutine to return an lvalue.@args). } sub nomod { $val. See the following example my $val.2.3). this doesn't work. don't say "return" $val. # assigns to $val in the above subroutine # ERROR Passing Lists to Subroutines: Because the @_ variable is an array. Lvalue subroutines: WARNING: Lvalue subroutines are still experimental and the implementation may change in future versions of Perl. nomod() = 5. $year. } Now see the magic canmod() = 5. @args = (2.$hour. it can be used to supply lists to a subroutine.48 ($sec.$yday. mysub(@args). sub canmod : lvalue { # return $val. Now the individual variables contain the corresponding values returned by localtime. To do this. then you need to use references: 48 .$mon.3). it can be difficult to extract the individual elements from @_.2. because of the way in which Perl accepts and parses lists and arrays.$mday.$isdst) = localtime(time). All the followings are valid mysub(1. However. @args = (1. o If you want to work with and identify the individual lists passed to Perl. It is possible to return a modifiable value from a subroutine. mysub(1.$min. Finally when we receive thes values in@_ variable then we can not recognize if we had passed one array or two value arraysbecause finally it is getting merged into one.$wday.3).

# De-reference the array list my (@lista) = @$listaref. we output the key/value pairs of the hash properly. so we can identify each list by assigning the reference to each array within our subroutine. A reference is actually just a scalar. $listbref ) = @_. the hash is automatically translated into a list of key/value pairs. so we can extract a list and convert it to a hash: sub display_hash { my (%hash) = @_. However. or pointer.. to the array. displaying each pair on its own line. Now you can write your subroutineas follows: sub simplesort { my ($listaref. \@listb). care needs to be taken if you expect to pick out a single hash from a list of arguments. foreach (%hash) { print "$_ => $hash{$_}\n". @listd) = simplesort(\@lista. As with arrays. The following will work because we extract the hash last: 49 . 'age' => 19). } Passing Hashes to Subroutines: When you supply a hash to a subroutine or operator that accepts a list. print %hash. The leading \ character tells Perl to supply a reference.nameTomage19. # Now you can play with both arrays. the same process works in reverse. This will output .49 (@listc. my (@listb) = @$listbref. } } In this case. For example: %hash = ('name' => 'Tom'.

then use references.t because we try to extract the hash first (there will be an extra element.Writing Reports: As stated earlier that Perl stands for Practical Extraction and Reporting Language. foreach my $key (keys %{$hasha}) { $newhash{$key} = $$hasha{$key} if (exists $$hashb{$key}). $regex) = @_. 'c' => 'b'). my %newhash.t know how to assign this to the hash): sub display_has_regexp { my (%hash. and Perl won. 'c' => 'b'.50 sub display_has_regexp { my ($regex.. %hash) = @_. . 'd' => 'b'). %newhash = intersection(\%hasha. and we'll now 50 . } return %newhash. 'b' => 'b'. $hashb) = @_. the following subroutine returns the key intersection of two hashes: sub intersection { my ($hasha. %hashb = ('b' => 'b'.. } while this one won. For example.. PERL Formats .. } To use the subroutine: %hasha = ('a' => 'b'. \%hashb). } If you want to work with multiple hashes. .

Other field holders include: @>>>> right-justified @|||| centered @####. A fieldholder has the format: @<<<< This fieldholder is left-justified. You must count the @ sign and the < signs to know the number of spaces in the field. value_two.51 discuss using Perl to write reports. You end the format with a single period. fieldline can contain any text or fieldholders. The fieldline is the specific way the data should be formatted. value_three fieldline value_one. To use the format feature of Perl. with a field space of 5. value_two . you must: • • • Define a Format Pass the data that will be displayed on the format Invoke the Format Define a Format Following is the syntax to define a Perl format format FormatName = fieldline value_one. Perl uses a writing template called a 'format' to output reports. Fieldholders hold space for data that will be placed there at a later date. The values lines represent the values that will be entered into the field line.## numeric field holder @* multiline field holder An example format would be: 51 . FormatName represents the name of the format.

First. however. to be associated with STDOUT. and using select along with this scalar variable after the special variable is assigned the format name. The above example will generate a report in the following format 52 .52 format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####. you could revert back to the original file handle by assigning the return value of select to a scalar value. In this example $name would be written as left justify within 22 character spaces and after that age will be written in two spaces. Remember: if you didn't have STDOUT set as your default file handle. using the select() function select(STDOUT). As we want the data sent to the STDOUT. and the write statement will send the output to this file handle. When we now do a write(). the data would be sent to STDOUT. we must make sure that that STDOUT is our selected file handle.## $salary =================================== . Invoke the Format to write Data In order to invoke this format declaration we would use the write keyword: write EMPLOYEE. using the special variable $~ $~ = "EMPLOYEE". We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT. #send to the output The problem is that the format name is usually the name of an open file handle. we must associate EMPLOYEE with the STDOUT filehandle.

Use $% vairable along with header as follows format EMPLOYEE_TOP = -----------------------Name Age -----------------------.53 Kirsten Mohammad Suhi Namrat 12 35 15 10 Defining a Report Header Everything looks fine. Now your report will look like -----------------------Name Age -----------------------Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 Defining a Pagination & Number of Lines on a Page What about if your report is taking more than one page ? You have a solution for that. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Page @< $% Now your output will look like 53 . Apart from defining a template you would have to define a header which will have same name but appended with _TOP keyword as follows format EMPLOYEE_TOP = -----------------------Name Age -----------------------.

you can define a footer and it will be written after each page. Error Handeling in PERL: You can identify and trap an error in a number of different ways. Its very easy to trap errors in Perl and then handeling them properly.54 -----------------------Name Age -----------------------Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 Page 1 You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ) By default $= will be 60 Defining a Report Footer One final thing is left which is footer.. for example: if (open(DATA. This will give you following result -----------------------Name Age -----------------------Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 End of Page 1 Page 1 For a complete set of variables related to formating. format EMPLOYEE_BOTTOM = End of Page @< $% . Very similar to header.$file)) { . Here are few methods which can be used.. } else 54 . please refer to Perl Sepcial Variables section. Here you will use _BOTTOM keyword instead of _TOP. Using if The if statement is the obvious choice when you need to check the return value from a statement.

For example. the simple module: 55 . and it reads nicely. except that it also calls exit. For example: unless(chdir("/etc")) { die "Error: Can't change directory!: $!". or when you specifically want to raise a module-related. The statement also makes sense when used in a single-line statement: die "Error: Can't change directory!: $!" unless(chdir("/etc")). • Reporting an error within a module that quotes the caller's information so that you can debug the line within the script that caused the error. Using unless The unless function is the logical opposite to if: statements can completely bypass the success status and only be executed if the expression returns false. Reporting Errors Within Modules: There are two different situations we need to be able to handle: • Reporting an error in a module that quotes the module's filename and line number . for example: die "Error: Something went wrong\n" if (error()). The conditional operator is best used when you want to quickly return one of two values within an expression or statement.55 { } die "Error: Couldn't open the file $!"."\n"). Errors raised in this fashion are useful to the end-user.a message is printed to STDERR. we can reduce the statement to one line in situations where it makes sense to do so. Here we die only if the chdir operation fails. The Die Function: The die function works just like warn. error. Using the Conditional Operator For very short tests. Within a normal script. chdir('/etc') or warn "Can't change directory".this is useful when debugging a module. this function has the effect of immediately terminating execution. because they highlight the error in relation to the calling script's origination line. The warn and die functions work slightly differently than you would expect when called from within a module. but the effect is the same as using an if or unless statement. Here variable $! returns the actual error message Alternatively. chdir('/etc') or die "Can't change directory". It's not quite so clear here what we are trying to achieve. The Warn Function: The warn function just raises a warning. but no further action is taken. } The unless statement is best used when you want to raise an error or alternative only if the expression fails. rather than script-related. you can use the conditional operator: print(exists($hash{value}) ? 'There' : 'Missing'.

pm line 11 T::function() called at S.pl line 3 The Croak Function The croak function is the equivalent of die.pm line 13 S::raise() called at test. @EXPORT = qw/function/. when called from a script use T. This would result in Error in module! at test. The Carp module provides four functions: carp. sub function { warn "Error in module!".pm line 11. and for all but the hardened programmer. this function also exits the script after reporting the error to STDERR: croak "Definitely didn't work". but not necessarily what you want. it completely pointless. which provides a simplified method for reporting errors within modules that return information about the calling script. function(). use Carp.pl line 3 The Cluck Function The cluck function is a sort of supercharged carp. the information is useful because it helps to point to a bug within the module itself. These functions are discussed below The Carp Function The carp function is the basic equivalent of warn and prints the message to STDERR without actually exiting the script and printing the script name. including information on the original script. cluck "Error in module!". This would result in something like Error in module! at T. } 1. require Exporter. croak.56 package T. Like die. except that it reports the caller one level up. the information provided is fairly useless. cluck. @ISA = qw/Exporter/. This would result in Error in module! at S. From a module programmer. and confess. it follows the same basic principle but also prints a stack trace of all the modules that led to the function being called. For an end-user.s perspective. This is more or less what you might expect. It will produce following result Error in module! at T.pm line 13 56 . The solution for such problems is the Carp module. carp "Error in module!".

The use sigtrap and even use diagnostics pragmas may also prove useful. • Long lines broken after an operator (except and and or). The Confess Function The confess function is like cluck. • One-line BLOCK may be put on one line. understand. You may turn it off explicitly for particular portions of code via the no warnings pragma or the $^W variable if you must. but there are some general guidelines that will make your programs easier to read. of course. • Blank lines between chunks that do different things. • No space before the semicolon. • Semicolon omitted in "short" one-line BLOCK. confess "Failed around about there". Here are some other more substantive style issues to think about: • Just because you CAN do something a particular way doesn't mean that you SHOULD do it that way. • Space after last parenthesis matching on current line. • Line up corresponding items vertically. This would result in Error in module! at T. • Space before the opening curly of a multi-line BLOCK. • Space around a "complex" subscript (inside brackets). Beyond that. • Opening curly on same line as keyword. have his or her own preferences in regards to formatting. and maintain The most important thing is to run your programs under the -w flag at all times. You should also always run under use strict or know the reason why not. • No space between function name and its opening parenthesis. he has other preferences that aren't so strong: • 4-column indent. so consider picking the most readable one. • Omit redundant punctuation as long as clarity doesn't suffer.pm line 11 T::function() called at S. • Uncuddled elses. Perl is designed to give you several ways to do anything. otherwise line up.pm line 13 S::raise() called at t2. Regarding aesthetics of code lay out.pl line 3 PERL Coding Standard: Each programmer will. about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. it calls die and then prints a stack trace all the way up to the origination script. if possible. For instance 57 . including curlies. the same basic rules apply regarding the including of line and file information according to the warn and die functions. • Space around most operators. • Space after each comma.57 As with carp.

last LINE if $foo. test the construct in an eval to see if it fails. For portability. statements. is better than $verbose && print "Starting analysis\n".$foo).58 open(FOO.. is better than die "Can't open $foo: $!" unless open(FOO. because the main point isn't • whether the user typed -v or not. when you just throw away their return values. that is. Avoid using grep() (or map()) or `backticks` in a void context. you can test $] ($PERL_VERSION in English) to see if it will be there. when Perl provides the last operator so you can exit in the middle. See the previous example. 58 . Just "outdent" it a little to make it more visible: LINE: for (. Those functions all have return values. because the second way hides the main point of the statement in a modifier.$foo) || die "Can't open $foo: $!". The Config module will also let you interrogate values determined by the Configure program when Perl was installed. On the other hand print "Starting analysis\n" if $verbose. } • • • Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. Otherwise use a foreach() loop or the system() function instead.) { statements. Don't go through silly contortions to exit a loop at the top or the bottom. so use them. when using features that may not be implemented on every machine. If you know what version or patchlevel a particular feature was implemented. next LINE if /^#/.

this information is given to the relevant applications which listen on different ports. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS. Consider. Always check the return codes of system calls. Don't use slash as a delimiter when your regexp has slashes or backslashes. include which program caused the problem. It is generally easier to read $var_names_like_this than $VarNamesLikeThis.. PERL Socket . If you can't remember what mnemonic means. Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Be consistent. oh. This information is routed to the system. For example a net browser listens on port 80 for information. use the /x modifier and put in some whitespace to make it look a little less like line noise. but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes. a typical computer system on a network receives and sends information as desired by the various applications running on it. use underscores to separate words in longer identifiers. never mind. If not for the socket. Taking a closer look. Other modules should begin with a capital letter and use mixed case.. you've got a problem. Consider giving away your code. especially for non-native speakers of English.Networking Programing: NOTE: If you are aware of Unix Sockets then you can leave introduction part What is a socket? Just another bit of computer jargon? Going back a little into networking history. If you have a really hairy regular expression. Consider writing a module or object class. what the failed system call and arguments were. While short identifiers like $gotit are probably ok. $dir) or die "can't opendir $dir: $!". For now. it is a Berkeley UNIX mechanism of creating a virtual duplex connection between processes. • • • Think about reusability. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. enabling connection. 59 . since a unique IP address is designated to it. Also we can write applications which listen and send information on a specific port number. let's sum up that a socket is an IP address and a port. Here's a simple but sufficient example: opendir(D. On the system. most of the network communication between systems would never ever have happened. Package names are sometimes an exception to this rule. Be nice. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider changing your whole world view.59 • • • • Choose mnemonic identifiers. Good error messages should go to STDERR. and (VERY IMPORTANT) should contain the standard system error message for what went wrong. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software.

Server uses bind() function to specify the port at which they will be accepting connections from the clients. The or die clause is very important . QUEUESIZE ). # the port bind( SOCKET. Creating A Client Create a socket The first step in establishing a network connection is creating a socket. Connect (the socket) to the remote machine with connect call. So socket function call will be something like this: use Socket #defines PF_INET and SOCK_STREAM socket(SOCKET. • • • DOMAIN should be PF_INET. ADDRESS ) binds a network ADDRESS to a SOCKET. The other three arguments are integers which should have the following values for TCP/IP connections. pack( 'Sn4x8'.SOCK_STREAM. TYPE should be SOCK_STREAM for TCP/IP connection.168 ) As the bind() is used by a server which does not need to know its own address so the argument list looks like this: $port = 12345. bind( SOCKET. AF_INET. $port. Accept client connections with accept call. Next socket function bind() fleshes out the socket with these values. DOMAIN.60 To explain the socket we will take an example of Client . 60 . To complete a client server architecture we would have to go through the following steps Creating A Server • • • • • • Create a socket with socket call. listen( SOCKET. It is the particular protocol such as TCP to be spoken over the socket.if a server dies without outstanding connections the port won't be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. with the sockt() function socket( SOCKET. PROTOCOL should be (getprotobyname('tcp'))[2]. The internet address of the computer ( for example 10. that's AF_INET. The address family (For TCP/IP.Server Programming. creates a socket socket creates a SOCKET. probably 2 on your system ) 2. Listen to the socket at the port address with listen call. ADDRESS is a socket address which ( for TCP/IP ) is a packet string containing three elements 1. Bind the socket to a port address with bind call.PF_INET. Here pack() function is being used to pack all the data into binary format.12. TYPE. Listening on the port If this is a server program then it is required to issue a call to listen() on the specified port.12. It's probable 2 on your computer. PROTOCOL ).(getprotobyname('tcp'))[2]). "\0\0\0\0" )) or die "Can't bind to port $port! \n". Bind to a socket address The sockets created by socket are innocent and they have not yet been polluted by a computer hostname or a port number. Create a socket with socket call. The port number ( for example 21 ) 3.

listen() is used in an infinite loop. # use port 7890 as default my $port = shift || 7890. pack( 'Sn4x8'.. connect( SOCKET. SOCKT ). } Now all the calls related to server are over and let us see a call which will be required by the client Connection Establishment If you are going to prepare client program then after using socket() call you would have to use another call connect() to connect to the server. PF_INET. SOCKET ). SOL_SOCKET.168". $server )) or die "Can't connect to port $port! \n".12. AF_INET. All future communication between client and server then takes place over NEW_SOCKET and SOCKET returns to what it does best : listen()ing for a new connection. # the ftp port $server_ip_address = "10.12. Here ADDRESS is a socket address similar to bind call. So now lets put all the things together Script to Create a Server #!/usr/bin/perl -w # server. $port. The accept call receive SOCKET descriptor returned by socket() function. You will often see accept() used inside a while loop as follows while(1) { accept( NEW_SOCKET. . Accepting connections If this is a server program then it is required to issue a call to access() function to accept the incoming connections. use Socket. my $proto = getprotobyname('tcp'). If you connect to the server successfully then you can start sending your commands to the server using SOCKET descriptor. Upon successful completion of this call.. make it reusable socket(SOCKET. $port = 21.. SO_REUSEADDR. As soon as one connection arrives the server deals with it and then goes back to listen for more connections... $proto) or die "Can't open socket $!\n".61 The above call is mandatory for all the servers and here QUEUESIZE is the maximum number of outstanding connection request allowed. SOCK_STREAM. 1) 61 .. except that it contains the IP address of the remote server.pl #-------------------use strict. ADDRESS ). # create a socket. setsockopt(SOCKET. a new socket descriptor is returned. Generally. accept( NEW_SOCKET. If access() call fails then it returns FLASE which is defined in Socket module which we have used initially. connect( SOCKET.

print "SERVER started on port $port\n". Namespaces prevent variable name collisions between packages Packages enable the construction of modules which. Writing PERL Modules: What are Packages? • • • • A package is a collection of code which lives in its own namespace A namespace is a named collection of unique variable names (also called a symbol table).12. SOCKET)) { # send them a message.pl #---------------use strict. connect to the port socket(SOCKET. pack( 'Sn4x8'.pl& Script to Create a Client #!/usr/bin/perl -w # client. connect( SOCKET.62 or die "Can't set socket option to SO_REUSEADDR $!\n".PF_INET. while ($line = <SOCKET>) { print "$line\n".(getprotobyname('tcp'))[2]) or die "Can't create a socket $!\n". $server )) or die "Can't connect to port $port! \n". my $port = shift || 7890. when used. close connection print NEW_SOCKET "Smile from the server". # bind to a port. # initialize host and port my $host = shift || 'localhost'. $port. then listen bind( SOCKET. my $line. $port. "\0\0\0\0" )) or die "Can't bind to port $port! \n". } Now starting above Server To run the server in background mode issue the following command on Unix prompt $sever. close NEW_SOCKET. listen(SOCKET. # create the socket.168". # accepting a connection my $client_addr. use Socket. 5) or die "listen: $!". while ($client_addr = accept(NET_SOCKET. AF_INET. } close SOCKET or die "close: $!".SOCK_STREAM. AF_INET.12. won't clobbber variables and functions outside of the modules's own namespace 62 . pack( 'Sn4x8'. my $server = "10.

The BEGIN and END blocks are particularly useful when creating Perl modules. You can explicitly refer to variables within a package using the :: package qualifier $PACKAGE_NAME::VARIABLE_NAME For Example: $i = 1. print "$i\n". print "$i\n". #!/usr/bin/perl package Foo. print "$i\n". # Prints "1" • • The package stays in effect until either another package statement is invoked.. sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } 63 . print "$i\n". A Perl module file called "Foo. } Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed Every END block is executed just before the perl interpreter exits. # Prints "1" print "$foo::i\n". # Prints "1" package foo. a new namespace is first created.. print "$i\n". BEGIN END { BEGIN END { • • • { . $i = 1.. } ...63 The Package Statement • • package statement switches the current naming context to a specified namespace (symbol table) If the named package does not exists. What are Perl Modules? A Perl module is a reusable package defined in a library file whose name is the same as the name of the package (with a . $i = 2. or until the end of the end of the current block or file. } . # Prints "1" package foo.pm on the end).. $i = 2. # Prints "2" package main.pm" might contain statements like this. # Prints "2" package main.. # Prints "2" BEGIN and END Blocks You may define any number of code blocks named BEGIN and END which act as constructors and destructors respectively. } { . print "$i\n"..

Then. hashes. @ISA = qw(Exporter). Foo::blat( "b" ).64 1. • Both use the list of search paths in @INC to find the module (you may modify it!) • Both call the eval function to process the code • The 1. subroutines. @ISA = qw(Exporter). Foo::bar( "a" ). Create the Perl Module Tree: When you are ready to ship your PERL module then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. require Exporter. provide a list of symbols (scalars. etc) by filling the list variable named @EXPORT: For Example package Module. The Use Function #!/usr/bin/perl use Foo. This utility comes alongwith PERL. @EXPORT = qw(bar blat). lists. Notice above that the subroutine names must be fully qualified (because they are isolated in their own package) It would be nice to enable the functions bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier. at the bottom causes eval to evaluate to TRUE (and thus not fail) The Require Function A module can be loaded by calling the require function #!/usr/bin/perl require Foo. Few noteable points about modules • The functions require and use will load a module. bar( "a" ). blat( "b" ). Here is the syntax to use h2xs 64 . sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } sub splat { print "Not $_[0]\n" } # Not exported! 1. A module can be loaded by calling the use function Notice that we didn't have to fully qualify the package's function names? The use function will export a list of symbols from a module given a few added statements inside a module require Exporter.

perl Makefile. Actual result is shown above. You would have to update README file with the proper instructions. where eXternal means external to Perl.PL Writing Person/README Writing Person/t/Person. lets understand references and anonymous arrays and hashes References • • • • A reference is. Use the following sequence to install any Perl Module.65 $h2xs -AX -n Module Name # For example. using the value of another variable. A symbolic reference enables you to refer to a variable by name. A hard reference refers to the actual data contained in a data structure.tar and you can ship it. i. Installing Perl Module: Installing a Perl Module is very easy.e. the symbolic reference to $foo refers to the variable $bar. • Changes • Makefile.PL • MANIFEST (contains the list of all files in the package) • README • t/ (test files) • lib/ ( Actual source code goes here So finally you tar this directory structure into a file Person. exactly as the name suggests. C) • -n specifies the name of the module So above command creates the following structure inside Person directory.PL make make install The Perl interpreter has a list of directories in which it searches for modules (global array @INC) Object Oriented Programming in PERL: Before we start Object Oriented concept of perl. if your module is available in Person.t Writing Person/Changes Writing Person/MANIFEST Here is the descritpion of these options • -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines) • -X omits XS elements (eXternal Subroutine. You can provide some test examples files in t directory. There are two types of references: symbolic and hard.pm file $h2xs -AX -n Person This will produce following result Writing Person/lib/Person.pm Writing Person/Makefile. a reference or pointer to another object. if the variable $foo contains the string "bar". For example. 65 .

# Create reference push (@$array. You can create more complex structures by nesting arrays: @arrayarray = ( 1. This line assigns an array. You can do the same with other variables: $array = \@ARGV. without creating an intervening named array . $glob = \*STDOUT. to the scalar $array. 'Woman' => 'Mary. @ for arrays. to dereference a scalar reference $foo. the third element is a reference to an anonymous array of three elements. &$foosub. $fooref = \$foo. To create a reference to a subroutine: sub foo { print "foo" }. The values on the right side of the assignment make up the array. print $glob "Hello World!\n". [1.66 Creating Hard References The unary backslash operator is used to create a reference to a named variable or subroutine. The $fooref variable now contains a hard reference to the $foo variable. Anonymous Arrays When you create a reference to an array directly . you would access the data as $$foo. # Create reference $hash = \%ENV.you are creating an anonymous array. 'Mary' ]. "From humans"). Creating an anonymous array is easy: $array = [ 'Bill'. except you use braces instead of square brackets: $hash = { 'Man' => 'Bill'. and the left side contains the reference to this array. # Create reference $foosub = \&foo. $$array[0] = 'Hello' $$hash{'Hello'} = 'World'. for example: $foo = 'Bill'. and & for subroutines) that you are expecting in front of the scalar variable containing the reference. 3]). # Create reference $glob = \*STDOUT. Anonymous Hashes Anonymous hashes are similarly easy to create. Dereferencing The most direct way of dereferencing a reference is to prepend the corresponding data type character ($ for scalars.that is. 'Ben. to to to to array hash typeglob subroutine Object Basics: 66 . $hash = \%ENV. indicated by the enclosing square brackets instead of the normal parentheses. For example. Other examples are: $array = \@ARGV. % for hashes. 'Dog' => 'Ben' }. 2. The @arrayarray now contains three elements. 2. $foosub = \&foo.

To create a class in Perl. One can use any kind of Perl variable as an object in Perl. Defining a Class: Its very simple to define a class. depending on whether the method affects the current object or the class. class. } 67 . print "Last Name is $self->{_lastName}\n". an object is merely a reference to a data type that knows what class it belongs to. which can be re-used over and over again. This constructor is a method defined within the package. print "First Name is $self->{_firstName}\n". a class is corresponds to a Package. • A method within Perl is a subroutine. The terms are object. }. For example: package Person. but in Perl one can use any name. explained from the point of view of how Perl handles objects. my $self = { _firstName => shift. When creating an object. return $self. The object reference is created by blessing a reference to the package's class. Creating and Using Objects: To create an instance of a class (an object) we need an object constructor. the same scalar can hold different objects in different classes. we first build a package. To declare a class named Person in Perl we do: package Person. # Print all the values just for clarification. $class. or until another package keyword is encountered. Most programmers choose to name this object constructor method new. Most Perl programmers choose either references to arrays or hashes. bless $self. sub new { my $class = shift. you need to supply a constructor. The object is stored as a reference in a scalar variable. Perl provides a bless() function which is used to return a reference and which becomes an object. _ssn => shift. Let's create our constructor for our Person class using a Perl hash reference. • Within Perl. A package is a self-contained unit of user-defined variables and subroutines.67 There are three main terms. In Perl. defined with the package. _lastName => shift. They provide a separate namespace within a Perl program that keeps subroutines and variables from conflicting with those in other packages. This is a subroutine within a package that returns an object reference. The first argument to the method is an object reference or a package name. The scope of the package definition extends to the end of the file. Because a scalar only contains a reference to the object. print "SSN is $self->{_ssn}\n". and method. • A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.

bless $self. Perl does not have private variables but we can still use the concept of helper functions methods and ask programmers to not mess with our object innards. Lets define a helper method to get person first name: sub getFirstName { return $self->{_firstName}. $self->{_firstName} = $firstName if defined($firstName). $firstName ) = @_. print "First Name is $self->{_firstName}\n". print "SSN is $self->{_ssn}\n". return $self->{_firstName}.68 Every method of a class passes first argument as class name. _lastName => shift. Now Let us see how to create an Object $object = new Person( "Mohammad". } Another helper function to set person first name: sub setFirstName { my ( $self. # Print all the values just for clarification. So in the above example class name would be "Person". my $self = { _firstName => shift. 23234345). 68 . }. $class. bless $self. sub new { my $class = shift. return $self.pm file #!/usr/bin/perl package Person. _ssn => shift. } Defining Methods: Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data directly and so provide accessor methods to modify object data. print "Last Name is $self->{_lastName}\n". For example package Person. my $self = {}. sub new { my $class = shift. You can try this out by printing value of $class. $class. You can use simple hash in your consturctor if you don't want to assign any value to any class variable. Next rest of the arguments will be rest of the arguments passed to the method. return $self. "Saleem". } Lets have a look into complete example: Keep Person package and helper functions into Person.

Inheritance: Object-oriented programming sometimes involves inheritance. then Perl gives up and raises a runtime exception. For example. # Get first name which is set using constructor. $self->{_firstName} = $firstName if defined($firstName). } 1. then Perl searches for the method within the UNIVERSAL class (package) that comes as part of the standard Perl library. $firstName = $object->getFirstName(). Following are noteable points while using inheritance • Perl searches the class of the specified object for the specified object. to help with this. $firstName = $object->getFirstName(). "Saleem". so you don't have to write the same code again and again. # Now get first name set by helper function. • If a matching method still cannot be found. • If no method is found in steps 1 or 2. $firstName ) = @_.pl fileas follows #!/usr/bin/perl use Person. called the Parent. then Perl uses an AUTOLOAD subroutine. print "Before Setting First Name is : $firstName\n". # Now Set first name using helper function. @ISA governs (method) inheritance. return $self->{_firstName}. return $self->{_firstName}. • Perl searches the classes defined in the object class's @ISA array. @ISA. $object->setFirstName( "Mohd." ). 23234345).69 } sub setFirstName { my ( $self. This will produce following result First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. 69 . This is referred to as an "isa" relationship because an employee is a person. we can have a class Employee which inherits from Person. Inheritance simply means allowing one class called the Child to inherit methods and attributes from another. print "Before Setting First Name is : $firstName\n". Perl has a special variable. $object = new Person( "Mohammad". Now create Person object in mail. • If the method still hasn't been found. } sub getFirstName { my( $self ) = @_. if one is found in the @ISA tree.

# Now get first name set by helper function. # Now Set first name using helper function.70 So to create a new Employee class that will inherit methods and attributes from our Person class." ). Person. $object = new Employee( "Mohammad". $firstName = $object->getFirstName(). use Person. # inherits from Person 70 . # Get first name which is set using constructor.pl file to test it #!/usr/bin/perl use Employee. # Call the constructor of the parent class. $_[2]. use Person. # Add few more attributes $self->{_id} = undef. our @ISA = qw(Person). our @ISA = qw(Person). Method Overriding: The child class Employee inherits all the methods from parent class Person. use strict. $firstName = $object->getFirstName(). use strict. This will produce following result First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. You can add your additional functions in child class. we simply code: Keep this code into Employee. But if you would like to override those methods in your child class then you can do it by givig your implementation. $object->setFirstName( "Mohd. # inherits from Person Now Employee Class has all the methods and attributes inherited from Person class and you can use it as follows: Use main. It can done as follows: modify Employee. "Saleem". # Override constructor sub new { my ($class) = @_.pm file #!/usr/bin/perl package Employee. 23234345). print "Before Setting First Name is : $firstName\n". my $self = $class->SUPER::new( $_[1]. $_[3] ).pm #!/usr/bin/perl package Employee. print "After Setting First Name is : $firstName\n".

return $self->{_lastName}. return $self->{_lastName}. } sub getLastName { my( $self ) = @_. #!/usr/bin/perl use Employee. Now put following code into main. # Now get first name set by helper function. } # Override helper function sub getFirstName { my( $self ) = @_. # This is child class function. $firstName = $object->getFirstName(). $class. $lastName ) = @_.pl and execute it. # Get first name which is set using constructor. $self->{_lastName} = $lastName if defined($lastName). } # Add more methods sub setLastName{ my ( $self. $firstName = $object->getFirstName(). print "Before Setting First Name is : $firstName\n". } 1. return $self->{_firstName}." ). This will produce following result First Name is Mohammad Last Name is Saleem SSN is 23234345 This is child class helper function Before Setting First Name is : Mohammad This is child class helper function After Setting First Name is : Mohd. return $self. "Saleem". Default Autoloading: 71 . bless $self.71 $self->{_title} = undef. # Now Set first name using helper function. $object = new Employee( "Mohammad". print "This is child class helper function\n". 23234345). print "After Setting First Name is : $firstName\n". $object->setFirstName( "Mohd.

unless (exists $self->{$field}) { croak "$field does not exist in object/class $type". then you will be aware of the need to create a . A destructor method is simply a member function (subroutine) named DESTROY which will be automatically called • • • • When the object reference's variable goes out of scope.. When the object reference's variable is undef-ed When the script terminates When the perl interpreter terminates For Example: package MyClass. Perl does this automatically for you as soon as the object goes out of scope. Here is an example to implement AUTOLOAD. In case you want to implement your destructore which should take care of closing files or doing some extra processing then you need to define a special method called DESTROY. the DESTROY method is just like any other. and you can do anything you like with the object in order to close it properly. to free the memory allocated to the object when you have finished using it. The name of the missing subroutine is accessible within this subroutine as $AUTOLOAD. 72 . you can implement this function in your way. If you define a function called AUTOLOAD() then any calls to undefined subroutines will call AUTOLOAD() function. This function is very useful for error handling purpose. This method will be called on the object just before Perl frees the memory allocated to it. my $field = $AUTOLOAD. } if (@_) { return $self->($name) = shift. } else { return $self->($name). my $type = ref ($self) || croak "$self is not an object". sub AUTOLOAD { my $self = shift. } } Destructors and Garbage Collection: If you have programmed using objects before. In all other respects. $field =~ s/. .72 Perl offers a feature which you would not find any many other programming languages: a default subroutine.*://. Put this source code into any file and execute it.. } Another OOP Example: Here is another nice example which will help you to understand Object Oriented Concepts of Perl.destructor. sub DESTROY { print " MyClass::DESTROY called\n".

73 . $type. $self->SUPER::MyMethod(). $myObject->MyMethod(). print " MySubClass::MyMethod called!\n". } # Following is the implemnetation of Inheritance. sub new { print " MyClass::new called\n". } # Here is the main program using above classes. # The package/type name my $self = {}. package MySubClass. package MyClass. } sub DESTROY { print " } MySubClass::DESTROY called\n". # The package/type name my $self = MyClass->new. } sub DESTROY { print " } MyClass::DESTROY called\n".73 #!/usr/bin/perl # Following is the implementation of simple Class. $myObject = MyClass->new(). package main. # Reference to empty hash return bless $self. my $type = shift. print "Invoke MyClass method\n". sub MyMethod { print " MyClass::MyMethod called!\n". $type. sub new { print " MySubClass::new called\n". my $type = shift. @ISA = qw( MyClass ). sub MyMethod { my $self = shift. # Reference to empty hash return bless $self.

MySQL or Informix etc. It defines a set of methods. This is clear from the following architure diagram. $myObject3 = MyClass->new().\n". allowing you to switch database implementations really easily. $myObject2 = MySubClass->new(). Here DBI is responsible of taking all SQL commands through the API. # Remaining destructors are called automatically here Database Management in PERL – DBI: This session will teach you how to access Oracle Database and other databases using PERL. • Oraperl Module to access Oracle. We will discuss this module in this chapter. DBI stands for Database independent interface for Perl which means DBI provides an abstraction layer between the Perl code and the underlying database. variables. print "Fall off the end of the script. You can use DBI whether you are working with Oracle.. and to dispatch them to the appropriate driver for actual execution. $myObject2->MyMethod(). And finally DBI is responsible of taking results from the driver and giving back it to the calling scritp. undef $myObject3. { my $myObject2 = MyClass->new(). } # Destructor is called automatically here print "Create and undef an object\n". or Application Programming Interface.74 print "Invoke MySubClass method\n". Notation and Conventions Throughout this chapter following notations will be used and it is recommended that you should 74 . Starting from Perl 5 it has become very easy to write database applications using DBI. Architecture of a DBI Application DBI is independent of any database available in backend.. print "Create a scoped object\n". and conventions that provide a consistent database interface. The DBI is a database access module for the Perl programming language. Check Oraperl Mnual • DBI module to access databases in generic way. independent of the actual database being used.

Following is the procedure to create single record into TEST_TABLE.75 also follow the same convention. $dbh = DBI->connect($dsn. $sth. Number of rows processed (if available. Following is the example of connecting with MySQL database "TESTDB" #!/usr/bin/perl use DBI use strict. my my my my my my $driver = "mysql". $password ) or die $DBI::errstr. LAST_NAME. else -1) A filehandle NULL values are represented by undefined values in Perl Reference to a hash of attribute values passed to methods Database Connection: Assuming we are going to work with MySQL database. If a connection is established with the datasource then a Database Handle is returned and saved into $dbh for further use otherwise $dbh is set to undef value and $DBI::errstr returns an error string. $database = "TESTDB". SEX and INCOME. • User ID "testuser" and password "test123" are set to access TESTDB • Perl Module DBI is installed properly on your machine. or $drh) General Return Code (boolean: true=ok. we are ready to create records into TEST_TABLE. $dsn $dbh $sth $h $rc $rv @ary $rows $fh undef \%attr Database source name Database handle object Statement handle object Any of the handle types above ($dbh. • You have created TEST_TABLE in TESTDB. $password = "test123". You can create many 75 . $userid = "testuser". Before connecting to a database make sure followings: • You have created a database TESTDB. $dsn = "DBI:$driver:database=$database". AGE. • You have gone through MySQL tutorial to understand MySQL Basics. INSERT Operation: INSERT operation is required when you want to create your records into TEST_TABLE. false=error) General Return Value (typically an integer) List of values returned from the database. • This table is having fields FIRST_NAME. $userid. So once our database connection is established.

LAST_NAME.76 records in similar fashion.?)").This will be done using 76 . Record creation takes following steps • Prearing SQL statement with INSERT statement. • Executing SQL query to select all the results from the database. • Executing SQL query to select all the results from the database. This will be done using finish() API • If everything goes fine then commit this operation otherwise you can rollback complete transaction. Following is the example. In such case binding values are used. $dbh->commit or die $DBI::errstr. $income) or die $DBI::errstr. READ Operation: READ Operation on any databasse means to fetch some useful information from the database. 'poul'. $age. $last_name = "poul".$last_name. • Releasing Stattement handle. AGE. LAST_NAME. $income = 13000. A question mark is used in place of actual value and then actual values are passed through execute() API. $dbh->commit or die $DBI::errstr. AGE. This will take four steps • Prearing SQL query based on required conditions. Following is the procedure to query all the records having AGE greater than 20. we are ready to make a query into this database. This will be done using execute() API. INCOME ) values ('john'. $sth->execute() or die $DBI::errstr. $sth->execute($first_name. SEX. $age = 30. This will be done using prepare() API. • Fetching all the results one by one and printing those results. So once our database connection is established. my $sth = $dbh->prepare("INSERT INTO TEST_TABLE (FIRST_NAME. 30.?.$sex. $sth->finish(). my my my my my my $first_name = "john". $sth->finish(). $sex = "M". Using Bind Values There may be a case when values to be entered is not given in advance. 'M'. SEX. INCOME ) values (?. $sth = $dbh->prepare("INSERT INTO TEST_TABLE (FIRST_NAME.?. Commit and Rollback are explained in next sections. This will be done using execute() API. 13000)"). This will be done using prepare() API.

print "First Name = $first_name. UPDATE Operation: UPDATE Operation on any databasse means to update one or more records already available in the database. print "Number of rows found :" + $sth->rows. This will take three steps • Prearing SQL query based on required conditions. } $sth->finish(). Following is the procedure to update all the records having SEX as 'M'. while (my @row = $sth->fetchrow_array()) { my ($first_name. Last Name = $last_name\n". This will be done using finish() API • If everything goes fine then commit this operation otherwise you can rollback complete transaction. $age = 20. } $sth->finish(). Releasing Stattement handle. LAST_NAME FROM TEST_TABLE WHERE AGE > 20"). • Executing SQL query to select all the results from the database. This will be done using execute() API. $sth->execute( $age ) or die $DBI::errstr. 77 .77 • my $sth = $dbh->prepare("SELECT FIRST_NAME. See next section for commit and rollback APIs. while (my @row = $sth->fetchrow_array()) { my ($first_name. print "Number of rows found :" + $sth->rows. $last_name ) = @row. LAST_NAME FROM TEST_TABLE WHERE AGE > ?"). $last_name ) = @row. print "First Name = $first_name. This will be done using prepare() API. This will be done using finish() API Using Bind Values There may be a case when condition is not given in advance. • Releasing Stattement handle. Here we will increase AGE of all the males by one year. my $sth = $dbh->prepare("SELECT FIRST_NAME. $sth->execute() or die $DBI::errstr. Last Name = $last_name\n". Following is the example. In such case binding values are used. A question mark is used in place of actual value and then actual value is passed through execute() API. fetchrow_array() API.

$sex = 'M'. $sth->execute( $income. • Releasing Stattement handle. • Prearing SQL query based on required conditions. 78 . A question mark is used in place of actual value and then actual value is passed through execute() API. This will be done using finish() API • If everything goes fine then commit this operation otherwise you can rollback complete transaction. In such case binding values are used. $income = 10000. '$sex') or die $DBI::errstr. $sth->finish(). This operation will take following steps. print "Number of rows updated :" + $sth->rows. my $sth = $dbh->prepare("UPDATE TEST_TABLE SET INCOME = ? WHERE SEX = ?"). $sth->execute() or die $DBI::errstr. Using Bind Values There may be a case when condition is not given in advance. Following is the example. Following is the procedure to delete all the records from TEST_TABLE where AGE is equal to 30. print "Number of rows updated :" + $sth->rows. This will be done using execute() API.78 my $sth = $dbh->prepare("UPDATE TEST_TABLE SET AGE = AGE + 1 WHERE SEX = 'M'"). my $sth = $dbh->prepare("UPDATE TEST_TABLE SET AGE = AGE + 1 WHERE SEX = ?"). DELETE Operation: DELETE operation is required when you want to delete some records from your database. print "Number of rows updated :" + $sth->rows. $dbh->commit or die $DBI::errstr. $dbh->commit or die $DBI::errstr. This will be done using prepare() API. • Executing SQL query to delete required records from the database. $sth->finish(). In some case you would like to set a value which is not given in advance so you can use binding value as follows. $sex = 'M'. In this example income of all males will be set to 10000. $sth->finish(). $age = 30. $sth->execute('$sex') or die $DBI::errstr.

cgi. lets see what happens when we click a hyper link to browse a particular web page or URL. and whatever that program outputs is sent back for your browser to display. • Web browser takes response from web server and displays either the received file or error message. C or C++ program etc. is a standard for external gateway programs to interface with information servers such as HTTP servers.1 and CGI/1. instead it is executed as a program. First CGI Program Here is a simple link which is linked to a CGI script called hello. 79 . Shell Script. CGI Architecture Diagram Web Server Support & Configuration Before you proceed with CGI Programming. filename. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows: The Common Gateway Interface. By convention PERL CGI files will have extention as .2 is under progress. The current version is CGI/1. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. • Web Server will parse the URL and will look for the filename in if it finds that file then sends back to the browser otherwise sends an error message indicating that you have requested a wrong file. This directory is called CGI Directory and by convention it is named as /cgi-bin.cgi UNIX command. Before running your CGI program make sure you have chage mode of file using chmod 755 hello. or CGI. is a set of standards that define how information is exchanged between the web server and a custom script. make sure that your Web Server supports CGI and it is configured to handle CGI Programs. These CGI programs can be a PERL Script. or CGI.79 PERL and CGI: What is CGI ? • • • The Common Gateway Interface. However. All the CGI Programs be executed by the HTTP server are kept in a pre-configured directory. Web Browsing To understand the concept of CGI.cgi. This file is being kept in /cgi-bin/ directory and it has following content. • Your browser contacts the HTTP web server and demand for the URL ie. it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back.

'<body>'. If you click hello. '<html>'. Now you must have been undertood basic concept of CGI and you can write many complicated CGI programs using PERL.First CGI Program</title>'. '<head>'. 80 . All the HTTP header will be in the following form HTTP Field Name: Field Content For Example Content-type:text/html\r\n\r\n There are few other important HTTP headers which you will use frequently in your CGI Programming. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\ r\n.80 #!/usr/bin/perl print print print print print print print print print 1. This script can interact with any other exertnal system also to exchange information such as RDBMS.cgi then this produces following output: "Content-type:text/html\r\n\r\n". HTTP Header: The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. This line is sent back to the browser and specifiy the content type to be displayed on the browser screen. '</html>'. '</head>'. screen. '</body>'. '<title>Hello Word . Hello Word! This is my first CGI program This hello.cgi script is a simple PERL script which is writing its output on STDOUT file ie. '<h2>Hello Word! This is my first CGI program</h2>'.

A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. Example is Contenttype:text/html Expires: Date String The date the information becomes invalid. of the data being returned. Content-length: String The length. This should be used by the browser to decide when a page needs to be refreshed.81 Header Description Content-type: String A MIME string defining the format of the file being returned. in bytes. You can use this filed to redirect a request to any file. Location: URL String The URL that should be returned instead of the URL requested. The 81 . Last-modified: String The date of last modification of the resource.

turn a BLOCK into a TERM dump .catch exceptions or compile and run code exec .optional trailing block in a while or foreach cos .remove the last character from a string chown .schedule a SIGALRM atan2 .get context of the current subroutine call chdir .be done using hosts file endnetent .82 PERL Functions References: Here is the list of all important functions supported by standard PERL Interpreter.test whether a hash key is present exit .be done using group file endhostent .changes the permissions on a list of files chomp .prepare binary files for I/O bless .deletes a value from a hash die . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • abs .binds an address to a socket binmode .create binding on a tied dbm file defined .one-way passwd-style encryption dbmclose .file control system call fileno .create an object caller .be done using passwd file endservent .breaks binding on a tied dbm file dbmopen . Click over a function to find its detail.test whether a value.arctangent of Y/X in the range -PI to PI bind .be done using services file eof .accept an incoming socket connect alarm .absolute value function accept .return file descriptor from filehandle 82 .raise an exception or bail out do .make directory new root for path lookups close . or function is defined or not delete .terminate this program exp .abandon this program to run another exists .remove a trailing record separator from a string chop .be done using protocols file endpwent .close file (or pipe or socket) handle closedir .connect to a remote socket continue .test a filehandle for its end eval .close directory handle connect . variable.create an immediate core dump each .be done using networks file endprotoent .get character this number represents chroot .raise I to a power fcntl .change your current working directory chmod .retrieve the next key/value pair from a hash endgrent .change the owership on a list of files chr .cosine function crypt .

get socket options on a given socket glob .declare a picture format with use by the write() function formline .lock an entire file with an advisory lock fork .get the next character from the filehandle getgrent .join a list into a string using a separator keys .get parent process ID getpriority .create a new process just like this one format .get passwd record given user ID getservbyname .get passwd record given user login name getpwuid .return a string with just the next letter in lower case length .create a hard link in the filesytem listen .get next hosts record getlogin .convert a string to a hexadecimal number import .send a signal to a process or process group last .expand filenames using wildcards gmtime .get the integer portion of a number ioctl .83 • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • flock .get process group getppid .system-dependent device control system call join .get next group record getgrgid . goto .get network record given its address getnetbyname .get current nice value getprotobyname .return lower-case version of a string lcfirst .get group record given group user ID getgrnam .find a substring within a string int .find the other end of a socket connection getpgrp .retrieve list of indices from a hash kill .exit a block prematurely lc .register your socket as a server 83 .patch a module's namespace into your own index .get protocol record numeric protocol getprotoent .return the number of bytes in a string link .get next networks record getpeername .retrieve the sockaddr for a given socket getsockopt .internal function used for formats getc .convert UNIX time into record or string using Greenwich time format.get host record given its address gethostbyname .get next passwd record getpwnam .return who logged in at this tty getnetbyaddr .get networks record given name getnetent .create spaghetti code grep .get next services record getsockname .get services record given numeric port getservent .get host record given name gethostent .get next protocols record getpwent .get services record given its name getservbyport .get group record given group name gethostbyaddr .locate elements in a list test true against a given criterion hex .get protocol record given name getprotobynumber .

convert a list into a binary representation package .fetch a record from a file readlink .retrieve the natural logarithm for a number lstat .fixed-length buffered input from a filehandle readdir .output a list to a filehandle printf .output a formatted list to a filehandle prototype .get SysV IPC message queue msgrcv .send a SysV IPC message to a message queue my .execute a system command and collect standard output recv .load in external functions from a library at runtime reset .retrieve the next pseudorandom number read .backquote quote a string rand .change a filename require .open a file.append one or more elements to an array q . subroutine.declare and assign a package variable (lexical scoping) pack .get out of a function early 84 .declare and assign a local variable (lexical scoping) next .get a directory from a directory handle readline .create a directory msgctl .declare a separate global namespace pipe .start this loop iteration over again ref .receive a SysV IPC message from a message queue msgsnd .unimport some module symbols or semantics at compile time oct .find out the type of thing being referenced rename .open a pair of connected filehandles pop .convert UNIX time into record or string using local time lock .find a character's numeric representation our .apply a change to a list to get back a new list with the changes mkdir .find or set the offset for the last/next m//g search print .stat a symbolic link m .open a directory ord .doubly quote a string qr .convert a string to an octal number open .84 • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • local .clear all variables of a given name return . or descriptor opendir .match a string with a regular expression pattern map .SysV IPC message control operations msgget .create a temporary value for a global variable (dynamic scoping) localtime .remove the last element from an array and return it pos . pipe.get a thread lock on a variable.quote regular expression magic characters qw . or method log .get the prototype (if any) of a subroutine push .determine where a symbolic link is pointing readpipe .receive a message over a Socket redo .quote a list of words qx .singly quote a string qq .iterate a block prematurely no .Compile pattern quotemeta .

SysV shared memory operations shmget .square root function srand .prepare group file for use sethostent .declare a subroutine. possibly anonymously substr .fixed-length unbuffered input from a filehandle sysseek .prepare protocols file for use setpwent .force a scalar context seek .get or alter a portion of a stirng symlink .sort a list of values splice .create a pair of sockets sort .get a file's status information study .prepare passwd file for use setservent . and return it shmctl .execute an arbitrary system call sysopen .create a symbolic link to a file syscall .formatted print into a string sqrt .SysV semaphore control operations semget .reposition file pointer for random-access I/O seekdir .flip a string or a list rewinddir .set some socket options shift .SysV semaphore operations send .reposition directory pointer select .write SysV shared memory shutdown .get set of SysV semaphores semop .close down just half of a socket connection sin .prepare hosts file for use setnetent .split up a string using a regexp delimiter sprintf .right-to-left substring search rmdir .seed the random number generator stat .remove a directory s .replace a pattern with a string scalar .create a socket socketpair . pipe.reset directory handle rindex .return the sine of a number sleep .remove the first element of an array.run a separate program 85 .read SysV shared memory shmwrite .reset default output or do I/O multiplexing semctl .set the process group of a process setpriority .prepare services file for use setsockopt .send a message over a socket setgrent .85 • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • reverse .add or remove elements anywhere in an array split .block for some number of seconds socket .position I/O pointer on handle used with sysread and syswrite system .optimize input data for repeated searches sub .get SysV shared memory segment identifier shmread .set a process's nice value setprotoent . or descriptor sysread .open a file.prepare networks file for use setpgrp .

return a string with just the next letter in upper case umask . etc) y .prepend more elements to the beginning of a list untie .print a picture record -X .transliterate a string< 86 .get current seekpointer on a directory handle tie .remove a variable or function definition unlink .shorten a file uc .break a tie binding to a variable use .convert binary structure into normal perl variables unshift .remove one link to a file unpack .wait for any child process to die waitpid .get a reference to the object underlying a tied variable time .transliterate a string truncate .set a file's last access and modify times values .set file creation mode mask undef .fixed-length unbuffered output to a filehandle tell .a file test (-r.return upper-case version of a string ucfirst .load in a module at compile time utime .bind a variable to an object class tied .return elapsed time for self and child processes tr .wait for a particular child process to die wantarray .get current seekpointer on a filehandle telldir .return number of seconds since 1970 times .return a list of the values in a hash vec .86 • • • • • • • • • • • • • • • • • • • • • • • • • • • • syswrite .get void vs scalar vs list context of current subroutine call warn . -x.print debugging info write .test or set particular bits in a string wait .

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->