24
Vamshi Krishna S

Introduction to perl_ a scripting language

Embed Size (px)

DESCRIPTION

Perl Presentation slides during 2011

Citation preview

Page 1: Introduction to perl_ a scripting language

Vamshi Krishna S

Page 2: Introduction to perl_ a scripting language

Practical Extraction and Report Language

‘A general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development-CGI scripting, network programming, GUI development, and more.’

‘The language is intended to be PRACTICAL (easy to use, efficient, complete) rather than

BEAUTIFUL (tiny, elegant, minimal).’

And Some More:

‘Many earlier computer languages, such as Fortran and C, were designed to make efficient use of expensive

computer hardware. In contrast, Perl is designed to make efficient use of expensive computer programmers.

Perl has many features that ease the programmer's task at the expense of greater CPU and memory requirements.

These include automatic memory management; dynamic typing; strings, lists, and hashes; regular expressions;

Page 3: Introduction to perl_ a scripting language

Larry Wall invented PERL in the mid-1980'sLarry Wall was trained as a linguist, and the design of Perl is very

much informed by linguistic principles. Examples include Huffman coding (common constructions should

be short), good end-weighting (the important information should

come first), and a large collection of language primitives. Perl favors language constructs that are natural for humans to

read and write, even where they complicate the Perl interpreter.’Perl has rapidly become the language of choice for writing

programs quickly and robustly across a wide range of fields - ranging from systems administration, text processing, linguistic analysis, molecular biology and (most importantly of all) the creation of dynamic World Wide Web pages. It has been estimated that about 80% of dynamic webpages worldwide are being created by Perl programs.

Page 4: Introduction to perl_ a scripting language

PERL encompasses both the syntactical rules of the language and the general ways in which programs are organized

It is dynamically typed language. Relatively easy to learn (and easier to make a

mess too). incredibly flexible coding style (some argues it is

too flexible). Perl is interpreted not complied hence its

scripting language. It follows OOPs concepts.

http://perldoc.perl.org/perldoc.html

Page 5: Introduction to perl_ a scripting language

CPAN(comprehensive Pern Archive Network) : consists of Additional perl modules(more than 100,000 modules), documentation,various releases etc., HTTP://cpan.org/

Page 6: Introduction to perl_ a scripting language

Define the problem Search for existing code Plan your solution Write the code

Modify ->Debug ->Modify Run the code

Page 7: Introduction to perl_ a scripting language

Now-a-days On *nix OSes Perl comes installed automatically. And can be located at /usr/bin/perl and /usr/local/bin/perl

To install Perl on Windows :

http://strawberryperl.com/

http://www.activestate.com/activeperl

Page 8: Introduction to perl_ a scripting language

Open a terminal Make a perl dir(directory) in your home

dir Move into the perl directory Create a file named ‘hello_world.pl’ Open the file in your text editor Code the program Save the file Make the program executable Test the program.

Page 9: Introduction to perl_ a scripting language

# Unix perl -e 'print "Hello world\n"‘

# MS-DOS perl -e "print \"Hello world\n\""

Page 10: Introduction to perl_ a scripting language

Location of perl is normally in /usr/bin/perl and /usr/local/bin/perl

Perfix the script with #!/usr/bin/perlAnd also you can type in “use <version>” to use the latest version

#!/usr/bin/perl -wuse strict;use warnings;

my $message = ‘Welcome to perl

tutorial’;

print “\t hello world $message.!!\n”; print ‘hello world $message.!!\n’

#prints $message\n literally

Page 11: Introduction to perl_ a scripting language

Scalar: a single piece of information. Scalars can hold numbers or text $ is the identifier of scalar in perl There are special variables for the system: $ARGV,

$! @scores = (32, 45, 16, 5); @cars = (BMW,Renault,Jaguar,Ferrari); or @cars =

qw(BMW Renault Jaguar Ferrari);

my @sorted = sort @cars; my @backwards = reverse @scores;

$multilined_string = <<EOF; This is my multilined string note that I am terminating it with the word "EOF". EOF

Scalar values are represented as $var = <num/char> ; Dynamic typing

Page 12: Introduction to perl_ a scripting language

Array/List: an ordered collection of scalars my @array = ( 1, 2 ); my @words = ( "first", "second", "third" ); my @mixed = ("camel", 42, 1.23);

print $mixed[$#mixed]; # last element, prints out 1.23

SubscriptsAn array can be accessed one scalar at a time by specifying a dollar sign ($ ), then the name of the array (without the leading @ ), then the subscript inside square brackets.

For example:@myarray = (5, 50, 500, 5000);print "The Third Element is", $myarray[2], "\n";

Page 13: Introduction to perl_ a scripting language

Declaration of HASHes %scientists =

(

"Newton" => "Isaac",

"Einstein" => "Albert",

"Darwin" => "Charles",

"Feynman" => "Richard",

);

print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";

Hash subscripts are similar, only instead of square brackets curly brackets are used

Page 14: Introduction to perl_ a scripting language

my %fruit_color = ("apple", "red", "banana", "yellow");

To get at hash elements:

$fruit_color{"apple"}; # gives "red“ To get a lists of keys and values

with keys() and values().

my @fruits = keys %fruit_colors;

my @colors = values %fruit_colors;

Page 15: Introduction to perl_ a scripting language

Some scalar variables have special meaning in Perl. Of note are `$_`,`$!`, `$0`, and `$$`.

Page 16: Introduction to perl_ a scripting language

There are system defined functions for operations on Scalar variables, Arrays, Hashes, File Handlers, Regular Expressions, Sub routines, Modules etc., which appear like keywords some times and take arguments

Eg: Chomp, join, my, our, grep, mkdir, open, import,defined,undef,sort,reverse etc.,

For detailed description follow: http://perldoc.perl.org/perlfunc.html#Perl-Functions-by-Category

Page 17: Introduction to perl_ a scripting language

double quotes(“), single quotes(‘) and multi-line quoting(qq) :$var =10;$text = “There are $var apples” $text2 = ‘There are $var apples’$text3 = qq{ There

are$var

apples};

Page 18: Introduction to perl_ a scripting language

Functions are blocks of code which perform specific task

#takes no input and returns no output… common practice to use #‘main’ as the starting point in a script.sub main { …}

#Takes 2 *scalars* as input sums them and returns one scalar.sub sum_2_numbers {

my ($numA,$numB) = @_; #get passed in values

my $sum = $numA+$numB; #sum numbersreturn($sum); #return sum

}

Page 19: Introduction to perl_ a scripting language

if/else if ( condition ) {…} elsif ( other condition ) {…} else {…}

Unlessdie "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';

While while (($key, $value) = each %hash) {

print $key, "\n";

delete $hash{$key};

}

Until$count = 10; until ($count == 0) { print "$count "; $count--;}

foreachforeach $index (0 .. $#ARRAY) {

delete $ARRAY[$index];

Page 20: Introduction to perl_ a scripting language

Logical operators: ==, !=, &&, ||, eq and ne

Page 21: Introduction to perl_ a scripting language

Undefined/” ”/0 values are treated as false

Scalars are evaluated as:numbers are evaluated as true if non-zerostrings are evaluated as true if non-empty

$var = “false”;

if($var)

{

say “$var is true!”;

}

Page 22: Introduction to perl_ a scripting language

Scripts can take inputs in two ways:Arguments

./print_args.pl ARG1 ARG2Prompted inputs from users

$user_text = <STDIN>

Page 23: Introduction to perl_ a scripting language

Things don’t always come out as expected. It is good to check the output of important functions for errors, it is highly recommended to validate any input from users or external sourcesDieWarn

Page 24: Introduction to perl_ a scripting language