Perl -Basic Programming concepts

Click here to load reader

download Perl -Basic Programming concepts

of 63

  • date post

  • Category


  • view

  • download


Embed Size (px)


Here are the basic of some Perl programming questions.

Transcript of Perl -Basic Programming concepts

PerlBy Tanuj Maheshwari

IntroductionPerl stands for "Practical Extraction and

Report Language" Created by Larry Wall when awk ran out of steam Perl grew at almost the same rate as the Unix operating system

Introduction (cont.)Perl fills the gaps between program

languages of different levels A great tool for leverage High portability and readily available

AvailabilityIt's free and runs rather nicely on nearly

everything that calls itself UNIX or UNIXlike Perl has been ported to the Amiga, the Atari ST, the Macintosh family, VMS, OS/2, even MS/DOS and Windows The sources for Perl (and many precompiled binaries for non-UNIX architectures) are available from the Comprehensive Perl Archive Network (the CPAN).

Running Perl on UnixSetup path variable to point to the

directory where Perl is located Check /usr/local/bin or /usr/bin for perl Run a Perl script by typing perl Alternatively, change the file attribute to executable and include #!/usr/bin/perl in the first line of your perl script The .pl extension is frequently associated to Perl scripts

Running Perl on Win32ActivePerl allows Perl scripts to be executed in

MS-DOS/Windows Perl is being ported faithfully The #! directive is no longer used because it does not mean anything to MS-DOS/Windows Perl scripts are executed by typing perl Alternatively, double clicking on the file if the extension .pl is being associated to the Perl interpreter

An Example#!/usr/bin/perl print Hello World!; The #! directive directs subsequent lines in the file to the perl executable All statements are terminated with ; as in C/C++/Java print by default outputs any strings to the terminal console. (such as printf in C or cout in C++) Perl completely parses and compiles the script before executing it

VariablesThree main types of variables, Scalar Array Hash Variables are all global in scope unless

defined to be private or local Note: remember that hash and array are used to hold scalar values

ExamplesAssigning values to a scalar

$i = hello world!; $j = 1 + 1; ($i,$j) = (2, 3)Assigning values to an array

$array[0] = 1; $array[1] = hello world!; push(@array,1); #stores the value 1 in the end of @array $value = pop(@array); #retrieves and removes the last element #from @array @array = (8,@array); #inserts 8 in front of @array

Examples (cont.)Assigning values to a hash

$hash{greeting} = Hello world!;

$hash{available} = 1; #or using a hash slice @hash{greeting,available} = (Hello world!, 1);Deleting a key-value pair from a hash:

delete $hash{key};

Conditional StatementsVariables alone will not support switches or

conditions If-Then-Else like clauses are used to make decisions based on certain preconditions Keywords: if, else, elsif, unless Enclosed by { and }

A Conditional Statement Exampleprint "What is your name? "; $name = ; chomp ($name); if ($name eq "Randal") { print "Hello, Randal! How good of you to be here!\n"; } else { print "Hello, $name!\n"; # ordinary greeting } unless($name eq Randal) { print You are not Randal!!\n; #part of the ordinary greeting }

$name = reads from standard

input chomp is a built-in function that removes

LoopsConditional statements cannot handle

repetitive tasks Keywords: while, foreach, for , until, do-while, do-until Foreach loop iterates over all of the elements in an array or hash, executing the loop body on each element For is a shorthand of while loop until is the reverse of while

Loops (cont.)Do-while and do-until loops executes the

loop body once before checking for termination Statements in the loop body are enclosed by { and }

While LoopSyntax: while(some expression){ statements; } Example:

#prints the numbers 1 10 in reverse order $a = 10; while ($a > 0) { print $a; $a = $a 1; }

Until LoopSyntax: until(some expression){ statements; } Example:

#prints the numbers 1 10 in reverse order $a = 10; until ($a $b") || die "cannot create $b: $!"; while () { # read a line from file $a into $_ print OUT $_; # print that line to file $b } close(IN) || die "can't close $a: $!"; close(OUT) || die "can't close $b: $!";

File I/O (cont.)File tests provides convenience for

programmers -e r w x d f l T B For example:

if(-f $name){ print $name is a file\n; } elsif(-d $name){ print $name is a directory\n; }

Special Variables$_, @_ $1, $2 - backreferencing variables

$_ = "this is a test"; /(\w+)\W+(\w+)/; # $1 is "this" and $2 is "is"$`, $& and $ - match variables

$string = this is a simple string; /si.*le/; #$& is now sample, $` is this is a and $ is #stringAnd many morerefer to ActivePerls online

documentations for their functions

Packages and ModulesConcentrate only on their usage in the

Greenstone environment Package: a mechanism to protect codes from tempering each others variables Module: reusable package that is stored in .dm The ppm (Perl Package Manager) for Linux and Win32 version of Perl manages installation and uninstallation of Perl packages

Packages and Modules (cont.)Install the module and put use ModuleName

or require ModuleName near the top of the program :: qualifying operator allow references to things in the package, such as $Module::Variable So use Math::Complex module refers to the module Math/ new creates an instance of the object, then use the handle and operator -> to access its functions

Packages and Modules (cont.)use accepts a list of strings as well, such that the

we can access the elements directly without the qualifying operator For example: use Module qw(const1 const2 func1 func2 func3); const1, const2, func1, func2 and func3 can now be used directly in the program

Packages and Modules (cont.)Perl locates modules by searching the @INC

array The first instance found will be used for the module referenced within a program Where to locate modules are an automatic process as the Makefiles and PPM take care placing modules in the correct path

Packages and Modules (cont.)An example that uses the package

use CGI; #uses the module $query = CGI::new(); #creates an instance of CGI $bday = $query->param("birthday"); #gets a named parameter print $query->header(); #outputs html header print $query->p("Your birthday is $bday."); #outputs text to html

Packages and Modules (cont.)Advantages: Encourages code reuse and

less work Disadvantages: 33% as fast as procedural Perl according to the book object-oriented Perl, generation of Perl modules involves some ugly codes

Packages and Modules (cont.)Huge library

ThanksTanuj maheshwari