SlideShare a Scribd company logo
ARRAYS, LISTS AND HASHES
By
SANA MATEEN
ARRAYS
 It is collections of scalar data items which have an assigned storage space in memory,
and can therefore be accessed using a variable name.
 The difference between arrays and hashes is that the constituent elements of an array are
identified by a numerical index, which starts at zero for the first element.
 array always starts with @, eg: @days_of_week.
 An array stores a collection, and list is a collection, so it is natural to assign a list to an
array. eg.
@rainfall=(1.2, 0.4, 0.3, 0.1, 0, 0 , 0);
This creates an array of seven elements. These can be accessed like
$rainfall[0], $rainfall[1], .... $rainfall[6].
A list can also occur as elements of other list.
@foo=(1,2,3, “string”);
@foobar= (4, 5, @foo, 6);
This gives foobar the value (4,5,1,2,3, “string”,6).
MANIPULATING ARRAYS
 Elements of an array are selected using C like square bracket syntax, eg: $bar=$foo[2].
 The $ and [ ] make it clear that this instance foo is an element of the array foo, not the
scalar variable foo.
 A group of contiguous elements is called a slice, and is accessed using simple syntax.
 @foo[1..3]
 Is the same as the list
($foo[1],$foo[2],$foo[3])
 The slice can be used as the destination of the assignment eg:@foo[1..3]= (“hop”, “skip”,
“jump”);
 Array variables and lists can be used interchangeably in almost any sensible situation:
$front=(“bob”, “carol”, “ted”, “alice”)[0];
@rest=(“bob”, “carol”, “ted”, “alice”) [1..3];
or even
@rest=qw/bob carol ted alice/[1..3];
Elements of an array can be selected by using another array selector.
 @foo =(7, “fred”, 9);
 @bar=(2,1,0);
then
@foo=@foo[@bar];
LISTS
 List is a collection of variables , constants or expressions which is to be
treated as a whole . It is written as comma separated sequence of values.
Eg: “red”, “green”, “blue”
 A list often appears in a script enclosed in round brackets.
(“red”, “green”, “blue”)
 Short hand used in lists: (1..8) and (“A”.. “H”, “O”.. “Z”).
 To save the tedious typing, qw(the quick brown fox)
 Is short hand for : (“the”, “quick”, “brown”, “fox”).
 qw- quote words operator, is an obvious extension of the q and qq operator.
 qw/the quick brown fox/ (or) qw|the quick brown fox|
 The list containing variables can appear as the target of an assignment and/or
as the value to be assigned.
($a , $b , $c)= (1,2,3);
MANIPULATING LISTS
 Perl provides several built-in functions for list manipulation. Three useful ones are a)shift
LIST b)unshift LIST c)push LIST
 a) returns the first item of the list and moves remaining items down reducing the size of the
list by 1.
 b) the opposite of shift: puts the items in LIST at the beginning of ARRAY, moving the
original contents up by the required amount.
 c) push LIST: It is similar to unshift but adds the values in LIST to the end of ARRAY
 ITERATING OVER LISTS
Perl provides a number of mechanisms to achieve this.
I. foreach
II. map
III. grep
 foreach loop: It performs a simple iteration over all the elements of a list.
foreach $item (list){
}
This blocks takes each value from the list and repeats execution.
foreach (@array){
.... #process $_
 map: perl provides an inbuilt function map to create plural forms of words.
 @p1=map $_. ‘s’ , @s;
 general form of map is: map expression, list;
 and map BLOCK list;
 we can also use foreach loop to achieve the same.
@s=qw/cat, dog, rabbit, hamster, rat/;
@p1=();
foreach (@s){
push @p1, $_. ‘s’
}
 grep : In unix grep is used to print all lines of the file which contains an instance of
pattern.
grep pattern file
The perl grep function takes a pattern and a list and returns new list containing all the
elements of the original list that match the pattern.
Eg: @things = (car, bus, cardigan, jumper, carrot);
grep /car/ @things
returns the list
(car,cardigan,carrot)
HASHES
 A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To
refer to a single element of a hash, you will use the hash variable name preceded by a
"$" sign and followed by the "key" associated with the value in curly brackets.
 Here is a simple example of using the hash variables −
 #!/usr/bin/perl
 %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
 print "$data{'John Paul'} = $data{'John Paul'}n";
 print "$data{'Lisa'} = $data{'Lisa'}n";
 print "$data{'Kumar'} = $data{'Kumar'}n";
 This will produce the following result −
 $data{'John Paul'} = 45
 $data{'Lisa'} = 30
 $data{'Kumar'} = 40
 CREATING HASHES
we can assign a list to an array, so it is not surprising that we can assign a list of key-value
pairs to a hash.
for example:
%foo= (key1, value1, key2, value2,.....);
alternative syntax is provided using the => operator to associate key-value pairs
%foo =(banana => ‘yellow’ , apple=>’green’ , ...)
Key Value(age)
John Paul 45
Lisa 30
Kumar 40
MANIPULATING HASHES
 Perl provides a number of built-in functions to facilitate manipulation of hashes. If we
have a hash called magic.
keys %magic
Returns a list of the keys of the elements in the hash.
values %magic
These functions provide way to iterate over the elements of hash using foreach:
foreach $key(keys %magic) {
do something with $magic($key)
}
Explicit loop variable is omitted, in which case the anonymous variable $_ will be assumed.
foreach(keys %magic)
{
process $magic($_);
}
An alternative is to use “each” operator which delivers successive key-value pairs from a hash.
while(($key,$value)=each %magic){
...
}
 Other useful operators for manipulating hashes are delete and exists.
 delete $magic($key)
 Removes the elements whose key matches $key from the hash %magic, and
 exists $magic($key)
 Returns true if the hash %magic contains an element whose key matches
$key.common idiomis
exists($h{‘key’})&&do(statements)
To avoid using an if statement.
STRINGS,PATTERNS AND
REGULAR EXPRESSIONS
BY
SANA MATEEN
INTRODUCTION TO REGULAR EXPRESSIONS
 It is a way of defining patterns.
 A notation for describing the strings produced by regular expression.
 The first application of regular expressions in computer system was in the text
editors ed and sed in the UNIX system.
 Perl provides very powerful and dynamic string manipulation based on the usage of
regular expressions.
 Pattern Match – searching for a specified pattern within string.
 For example:
 A sequence motif,
 Accession number of a sequence,
 Parse HTML,
 Validating user input.
 Regular Expression (regex) – how to make a pattern match.
HOW REGEX WORK
Regex
code
Perl
compiler
Input data (e.g. sequence file)
outputregex engine
SIMPLE PATTERNS
 Place the regex between a pair of forward slashes ( / / ).
 try:
 #!/usr/bin/perl
 while (<STDIN>) {
 if (/abc/) {
 print “>> found ‘abc’ in $_n”;
 }
 }
 Save then run the program. Type something on the terminal then press return.
Ctrl+C to exit script.
 If you type anything containing ‘abc’ the print statement is returned.
STAGES
1. The characters
 | ( ) [ { ^ $ * + ? .
are meta characters with special meanings in regular expression. To use
metacharacters in regular expression without a special meaning being
attached, it must be escaped with a backslash. ] and } are also metacharacters
in some circumstances.
2. Apart from meta characters any single character in a regular expression /cat/
matches the string cat.
3. The meta characters ^ and $ act as anchors:
^ -- matches the start of the line
$ -- matches the end of the line.
so regex /^cat/ matches the string cat only if it appears at the start of the
line.
/cat$/ matches only at the end of the line.
/^cat$/ matches the line which contains the string cat and /^$/ matches
an empty line.
4. The meta character dot (.) matches any single character except newline,
so/c.t/ matches cat,cot,cut, etc.
STAGES
5. A character class is set of characters enclosed in square brackets. Matches any single
character from those listed.
So /[aeiou]/- matches any vowel
/[0123456789]/-matches any digit
Or /[0-9]/
6. A character class of the form /[^....]/ matches any characters except those listed, so
/[^0-9]/ matches any non digit.
7. To remove the special meaning of minus to specify regular expression to match
arithmetic operators.
/[+-*/]/
8. Repetition of characters in regular expression can be specified by the quantifiers
* -- zero or more occurrences
+ -- one or more occurrences
? – zero or more occurrences
9. Thus /[0-9]+/ matches an unsigned decimal number and /a.*b/ matches a substring
starting with ‘a’ and ending with ‘b’, with an indefinite number of other characters in
between.
FACILITIES
1. Alternations |
If RE1,RE2,RE3 are regular expressions, RE1|RE2|RE3 will match any one of the
components.
2. Grouping- ( )
Round Brackets can be used to group items.
/pitt the (elder|younger)/
3. Repetition counts
Explicit repetition counts can be added to a component of regular expression
/(wet[]){2}wet/ matches ‘ wet wet wet’
Full list of possible count modifiers are
{n} – must occur exactly n times
{n,} –must occur at least n times
{n,m}- must occur at least n times but no more than m times.
4. Regular expression
 Simple regex to check for an IP address:
 ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$
FACILITIES
5. Non-greedy matching
A pattern including
.* matches the longest string it can find.
The pattern .*? Can be used when the shortest match is required.
? – shortest match
6.Short hand
This notation is given for frequent occurring character classes.
d – matches- digit
w – matches – word
s- matches- whitespace
D- matches any non digit character
Capitalization of notation reverses the sense
7. Anchors
b – word boundary
B – not a word boundary
/bJohn/ -matches both the target string John and Johnathan.
8. Back References
Round brackets define a series of partial matches that are remembered for use in subsequent processing or
in the RegEx itself.
9. The Match Operator
The match operator, m//, is used to match a string or statement to a regular expression. For example, to
match the character sequence "foo" against the scalar $bar, you might use a statement like this:
if ($bar =~ /foo/)
Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator,
BINDING OPERATOR
 Previous example matched against $_
 Want to match against a scalar variable?
 Binding Operator “=~” matches pattern on right against string on left.
 Usually add the m operator – clarity of code.
 $string =~ m/pattern/
MATCHING ONLY ONCE
 There is also a simpler version of the match operator - 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.
 For example, you can use this to get the first and last elements within a list:
 To remember which portion of string matched we use $1,$2,$3 etc
 #!/usr/bin/perl
 @list = qw/food foosball subeo footnote terfoot canic footbrdige/;
 foreach (@list) {
 $first = $1 if ?(foo.*)?; $last = $1 if /(foo.*)/;
 }
 print "First: $first, Last: $lastn";
 This will produce following result First: food, Last: footbrdige
s/PATTERN/REPLACEMENT/;
$string =~ s/dog/cat/;
#/user/bin/perl
$string = 'The cat sat on the mat';
$string =~ s/cat/dog/;
print "Final Result is $stringn";
This will produce following result
The dog sat on the mat
THE SUBSTITUTION OPERATOR
The substitution operator, s///, is really just an extension of the match operator that allows you to
replace the text matched with some new text. The basic form of the operator is:
The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want to use to
replace the found text with.
For example, we can replace all occurrences of .dog. with .cat. Using
Another example:
PATTERN MATCHING MODIFIERS
 m//i – Ignore case when pattern matching.
 m//g – Helps to count all occurrence of substring.
$count=0;
while($target =~ m/$substring/g) {
$count++
}
 m//m – treat a target string containing newline characters as multiple
lines.
 m//s –Treat a target string containing new line characters as single string, i.e
dot matches any character including newline.
 m//x – Ignore whitespace characters in the regular expression unless
they occur in character class.
 m//o – Compile regular expressions once only
THE TRANSLATION OPERATOR
 Translation is similar, but not identical, to the principles of substitution, but
unlike substitution, translation (or transliteration) does not use regular
expressions for its search on replacement values. 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, using the "The cat sat on the mat." string
 #/user/bin/perl
 $string = 'The cat sat on the mat';
 $string =~ tr/a/o/;
 print "$stringn";
 When above program is executed, it produces the following result −
 The cot sot on the mot.
TRANSLATION OPERATOR MODIFIERS
 Standard Perl ranges can also be used, allowing you to specify ranges of characters
either by letter or numerical value.
 To change the case of the string, you might use the following syntax in place of
the uc function.
 $string =~ tr/a-z/A-Z/;
 Following is the list of operators related to translation.
Modifier Description
c Complements SEARCHLIST
d Deletes found but unreplaced
characters
s Squashes duplicate replaced
characters.
SPLIT
 Syntax of split
 split REGEX, STRING will split the STRING at every match of the REGEX.
 split REGEX, STRING, LIMIT where LIMIT is a positive number. This will
split the STRING at every match of the REGEX, but will stop after it found LIMIT-
1 matches. So the number of elements it returns will be LIMIT or less.
 split REGEX - If STRING is not given, splitting the content of $_, the default
variable of Perl at every match of the REGEX.
 split without any parameter will split the content of $_ using /s+/ as REGEX.
 Simple cases
 split returns a list of strings:
 use Data::Dumper qw(Dumper); # used to dump out the contents of any
variable during the running of a program
 my $str = "ab cd ef gh ij";
 my @words = split / /, $str;
 print Dumper @words;
 The output is:
 $VAR1 = [ 'ab', 'cd', 'ef', 'gh', 'ij' ];
SUBSROUTINES IN PERL
BY
SANA MATEEN
WHAT IS SUBROUTINE?
 A Perl subroutine or function is a group of statements that together performs a task. You
can divide up your code into separate subroutines. How you divide up your code among
different subroutines is up to you, but logically the division usually is so each function
performs a specific task.
 Perl uses the terms subroutine, method and function interchangeably.
 The simplest way for reusing code is building subroutines.
 They allow executing the same code in several places in your application, and they allow
it to be executed with different parameters.
 Define and Call a Subroutine
 The general form of a subroutine definition in Perl programming language is as follows −
 sub subroutine_name
 { body of the subroutine
 }
 The typical way of calling that Perl subroutine is as follows −
 subroutine_name( list of arguments );
 Or
 &subroutine_name(earlier way);
Because Perl compiles your program before executing it, it doesn't matter where
you declare your subroutine.
#
# Main Code
# pseudo-code
..set variables
.
call sub1
.
call sub2
.
call sub3
.
exit program
sub 1
# code for sub 1
exit subroutine
sub 2
# code for sub 2
exit subroutine
sub 3
# code for sub 3
call sub 4
exit subroutine
sub 4
# code sub4
exit
PROGRAM(CODE) DESIGN USING
SUBROUTINES
-PSEUDO CODE
PASSING ARGUMENTS TO A SUBROUTINE
 You can pass various arguments to a subroutine like you do in any other programming
language and they can be accessed inside the function using the special array @_. Thus
the first argument to the function is in $_[0], the second is in $_[1], and so on.
 You can pass arrays and hashes as arguments like any scalar but passing more than
one array or hash normally causes them to lose their separate identities. So we will
use references to pass any array or hash.
 Let's try the following example, which takes a list of numbers and then prints their
average −
PASSING LISTS TO SUBROUTINES
 Because the @_ variable is an array, it can be used to supply lists to a subroutine.
However, because of the way in which Perl accepts and parses lists and arrays, it can
be difficult to extract the individual elements from @_. If you have to pass a list
along with other scalar arguments, then make list as the last argument as
shown below −
PASSING HASHES TO SUBROUTINES
 When you supply a hash to a subroutine or operator that accepts a list, then hash is
automatically translated into a list of key/value pairs. For example −
RETURNING VALUE FROM A SUBROUTINE
 You can return a value from subroutine like you do in any other programming language. If you are
not returning a value from a subroutine then whatever calculation is last performed will
automatically returns value.
 You can return arrays and hashes from the subroutine like any scalar but returning more than one
array or hash normally causes them to lose their separate identities. So we will use references to
return any array or hash from a function.
 Let's try the following example, which takes a list of numbers and then returns their average −
PRIVATE VARIABLES IN A SUBROUTINE
 By default, all variables in Perl are global variables, which means they
can be accessed from anywhere in the program. But you can
create private variables called lexical variables at any time with
the my operator.
 The my operator confines a variable to a particular region of code in
which it can be used and accessed. Outside that region, this variable
cannot be used or accessed. This region is called its scope. A lexical
scope is usually a block of code with a set of braces around it, such as
those defining the body of the subroutine or those marking the code
blocks of if, while, for, foreach, and evalstatements.
 Following is an example showing you how to define a single or multiple
private variables using my operator −
 sub somefunc {
 my $variable; # $variable is invisible outside somefunc()
 my ($another, @an_array, %a_hash); # declaring many variables at
once
 }
The following example distinguishes between global variable and private variable.
ADVANTAGES OF SUBROUTINES
 Saves typing → fewer lines of code →less likely to make a mistake
 re-usable
 if subroutine needs to be modified, can be changed in only one
place
 other programs can use the same subroutine
 can be tested separately
 makes the overall structure of the program clearer

More Related Content

What's hot

Genetic markers-SSS
Genetic markers-SSSGenetic markers-SSS
Genetic markers-SSS
Shashank Shekhar Solankey
 
Variant (SNPs/Indels) calling in DNA sequences, Part 2
Variant (SNPs/Indels) calling in DNA sequences, Part 2Variant (SNPs/Indels) calling in DNA sequences, Part 2
Variant (SNPs/Indels) calling in DNA sequences, Part 2
Denis C. Bauer
 
08.13.08: DNA Sequence Variation
08.13.08: DNA Sequence Variation08.13.08: DNA Sequence Variation
08.13.08: DNA Sequence Variation
Open.Michigan
 
Functional genomics
Functional genomicsFunctional genomics
Functional genomics
Ajit Shinde
 
Gene expression introduction
Gene expression introductionGene expression introduction
Gene expression introduction
Setia Pramana
 
Single nucleotide polymorphism
Single nucleotide polymorphismSingle nucleotide polymorphism
Single nucleotide polymorphism
Simon Silvan
 
genome mapping
genome mappinggenome mapping
genome mapping
Suresh San
 
Blast fasta
Blast fastaBlast fasta
Blast fastayaghava
 
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
Banoth Madhu
 
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICSSTRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
SHEETHUMOLKS
 
Comparitive genome mapping and model systems
Comparitive genome mapping and model systemsComparitive genome mapping and model systems
Comparitive genome mapping and model systems
Himanshi Chauhan
 
SNP Genotyping Technologies
SNP Genotyping TechnologiesSNP Genotyping Technologies
SNP Genotyping Technologies
SivamaniBalasubramaniam
 
Scoring schemes in bioinformatics
Scoring schemes in bioinformaticsScoring schemes in bioinformatics
Scoring schemes in bioinformatics
SumatiHajela
 
Illumina infinium sequencing
Illumina infinium sequencingIllumina infinium sequencing
Illumina infinium sequencing
Ayush Jain
 
FISH and GISH : Chromosome painting
FISH and GISH : Chromosome paintingFISH and GISH : Chromosome painting
FISH and GISH : Chromosome painting
Mahesh Hampannavar
 
SEMINAR ON CRISPR
SEMINAR ON CRISPRSEMINAR ON CRISPR
SEMINAR ON CRISPR
Man Mohan Soni
 
markers and their role
markers and their rolemarkers and their role
markers and their role
GOPICHAND JADHAO
 
Blast gp assignment
Blast  gp assignmentBlast  gp assignment
Blast gp assignment
barathvaj
 
Structural Genomics
Structural GenomicsStructural Genomics
Structural Genomics
Aqsa Javed
 
Association mapping
Association mappingAssociation mapping
Association mapping
Senthil Natesan
 

What's hot (20)

Genetic markers-SSS
Genetic markers-SSSGenetic markers-SSS
Genetic markers-SSS
 
Variant (SNPs/Indels) calling in DNA sequences, Part 2
Variant (SNPs/Indels) calling in DNA sequences, Part 2Variant (SNPs/Indels) calling in DNA sequences, Part 2
Variant (SNPs/Indels) calling in DNA sequences, Part 2
 
08.13.08: DNA Sequence Variation
08.13.08: DNA Sequence Variation08.13.08: DNA Sequence Variation
08.13.08: DNA Sequence Variation
 
Functional genomics
Functional genomicsFunctional genomics
Functional genomics
 
Gene expression introduction
Gene expression introductionGene expression introduction
Gene expression introduction
 
Single nucleotide polymorphism
Single nucleotide polymorphismSingle nucleotide polymorphism
Single nucleotide polymorphism
 
genome mapping
genome mappinggenome mapping
genome mapping
 
Blast fasta
Blast fastaBlast fasta
Blast fasta
 
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
Genomic In-Situ Hybridization (GISH)-Principles, Methods and Applications in ...
 
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICSSTRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
STRUCTURAL GENOMICS, FUNCTIONAL GENOMICS, COMPARATIVE GENOMICS
 
Comparitive genome mapping and model systems
Comparitive genome mapping and model systemsComparitive genome mapping and model systems
Comparitive genome mapping and model systems
 
SNP Genotyping Technologies
SNP Genotyping TechnologiesSNP Genotyping Technologies
SNP Genotyping Technologies
 
Scoring schemes in bioinformatics
Scoring schemes in bioinformaticsScoring schemes in bioinformatics
Scoring schemes in bioinformatics
 
Illumina infinium sequencing
Illumina infinium sequencingIllumina infinium sequencing
Illumina infinium sequencing
 
FISH and GISH : Chromosome painting
FISH and GISH : Chromosome paintingFISH and GISH : Chromosome painting
FISH and GISH : Chromosome painting
 
SEMINAR ON CRISPR
SEMINAR ON CRISPRSEMINAR ON CRISPR
SEMINAR ON CRISPR
 
markers and their role
markers and their rolemarkers and their role
markers and their role
 
Blast gp assignment
Blast  gp assignmentBlast  gp assignment
Blast gp assignment
 
Structural Genomics
Structural GenomicsStructural Genomics
Structural Genomics
 
Association mapping
Association mappingAssociation mapping
Association mapping
 

Viewers also liked

Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
sana mateen
 
Unit 1-perl names values and variables
Unit 1-perl names values and variablesUnit 1-perl names values and variables
Unit 1-perl names values and variables
sana mateen
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
sana mateen
 
Unit 1-subroutines in perl
Unit 1-subroutines in perlUnit 1-subroutines in perl
Unit 1-subroutines in perl
sana mateen
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
sana mateen
 
Unit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scriptingUnit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scripting
sana mateen
 
Unit 1-introduction to scripts
Unit 1-introduction to scriptsUnit 1-introduction to scripts
Unit 1-introduction to scripts
sana mateen
 
BABoK V2 Business Analysis Planning and Monitoring (BAPM)
BABoK V2 Business Analysis Planning and Monitoring (BAPM)BABoK V2 Business Analysis Planning and Monitoring (BAPM)
BABoK V2 Business Analysis Planning and Monitoring (BAPM)
AMJAD SHAIKH
 
How to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slidesHow to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slides
otikik
 
Visual Data Representation Techniques Combining Art and Design
Visual Data Representation Techniques Combining Art and DesignVisual Data Representation Techniques Combining Art and Design
Visual Data Representation Techniques Combining Art and Design
Logo Design Guru
 
Tweet Tweet Tweet Twitter
Tweet Tweet Tweet TwitterTweet Tweet Tweet Twitter
Tweet Tweet Tweet TwitterJimmy Jay
 
16 things that Panhandlers can teach us about Content Marketing
16 things that Panhandlers can teach us about Content Marketing16 things that Panhandlers can teach us about Content Marketing
16 things that Panhandlers can teach us about Content Marketing
Brad Farris
 
Cubicle Ninjas' Code of Honor
Cubicle Ninjas' Code of HonorCubicle Ninjas' Code of Honor
Cubicle Ninjas' Code of HonorCubicle Ninjas
 
Email and tomorrow
Email and tomorrowEmail and tomorrow
Email and tomorrow
Louis Richardson
 
Hashtag 101 - All You Need to Know About Hashtags
Hashtag 101 - All You Need to Know About HashtagsHashtag 101 - All You Need to Know About Hashtags
Hashtag 101 - All You Need to Know About Hashtags
Modicum
 
The Do's and Don'ts of Presentations
The Do's and Don'ts of Presentations The Do's and Don'ts of Presentations
The Do's and Don'ts of Presentations Cubicle Ninjas
 
Using Color to Convey Data in Charts
Using Color to Convey Data in ChartsUsing Color to Convey Data in Charts
Using Color to Convey Data in Charts
ZingChart
 
The no bullet bullet slide
The no bullet bullet slideThe no bullet bullet slide
The no bullet bullet slide
Gavin McMahon
 
Amazing First Slide Picture Templates
Amazing First Slide Picture Templates Amazing First Slide Picture Templates
Amazing First Slide Picture Templates
Abhishek Shah
 
Weekly Inspirational Quotes by Fun Team Building
Weekly Inspirational Quotes by Fun Team BuildingWeekly Inspirational Quotes by Fun Team Building
Weekly Inspirational Quotes by Fun Team Building
Fun Team Building
 

Viewers also liked (20)

Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
Unit 1-perl names values and variables
Unit 1-perl names values and variablesUnit 1-perl names values and variables
Unit 1-perl names values and variables
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
Unit 1-subroutines in perl
Unit 1-subroutines in perlUnit 1-subroutines in perl
Unit 1-subroutines in perl
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
 
Unit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scriptingUnit 1-uses for scripting languages,web scripting
Unit 1-uses for scripting languages,web scripting
 
Unit 1-introduction to scripts
Unit 1-introduction to scriptsUnit 1-introduction to scripts
Unit 1-introduction to scripts
 
BABoK V2 Business Analysis Planning and Monitoring (BAPM)
BABoK V2 Business Analysis Planning and Monitoring (BAPM)BABoK V2 Business Analysis Planning and Monitoring (BAPM)
BABoK V2 Business Analysis Planning and Monitoring (BAPM)
 
How to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slidesHow to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slides
 
Visual Data Representation Techniques Combining Art and Design
Visual Data Representation Techniques Combining Art and DesignVisual Data Representation Techniques Combining Art and Design
Visual Data Representation Techniques Combining Art and Design
 
Tweet Tweet Tweet Twitter
Tweet Tweet Tweet TwitterTweet Tweet Tweet Twitter
Tweet Tweet Tweet Twitter
 
16 things that Panhandlers can teach us about Content Marketing
16 things that Panhandlers can teach us about Content Marketing16 things that Panhandlers can teach us about Content Marketing
16 things that Panhandlers can teach us about Content Marketing
 
Cubicle Ninjas' Code of Honor
Cubicle Ninjas' Code of HonorCubicle Ninjas' Code of Honor
Cubicle Ninjas' Code of Honor
 
Email and tomorrow
Email and tomorrowEmail and tomorrow
Email and tomorrow
 
Hashtag 101 - All You Need to Know About Hashtags
Hashtag 101 - All You Need to Know About HashtagsHashtag 101 - All You Need to Know About Hashtags
Hashtag 101 - All You Need to Know About Hashtags
 
The Do's and Don'ts of Presentations
The Do's and Don'ts of Presentations The Do's and Don'ts of Presentations
The Do's and Don'ts of Presentations
 
Using Color to Convey Data in Charts
Using Color to Convey Data in ChartsUsing Color to Convey Data in Charts
Using Color to Convey Data in Charts
 
The no bullet bullet slide
The no bullet bullet slideThe no bullet bullet slide
The no bullet bullet slide
 
Amazing First Slide Picture Templates
Amazing First Slide Picture Templates Amazing First Slide Picture Templates
Amazing First Slide Picture Templates
 
Weekly Inspirational Quotes by Fun Team Building
Weekly Inspirational Quotes by Fun Team BuildingWeekly Inspirational Quotes by Fun Team Building
Weekly Inspirational Quotes by Fun Team Building
 

Similar to Unit 1-array,lists and hashes

Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
sana mateen
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
DurgaNayak4
 
Lists and arrays
Lists and arraysLists and arrays
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
Max Kleiner
 
Introduction to perl_control structures
Introduction to perl_control structuresIntroduction to perl_control structures
Introduction to perl_control structures
Vamshi Santhapuri
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
Ben Brumfield
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Perl programming language
Perl programming languagePerl programming language
Perl programming languageElie Obeid
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
Vamshi Santhapuri
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
First steps in PERL
First steps in PERLFirst steps in PERL
First steps in PERL
Brahma Killampalli
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaj Gupta
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
Jalpesh Vasa
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlSway Wang
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
Nithin Kumar Singani
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
Chris Chubb
 

Similar to Unit 1-array,lists and hashes (20)

Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Introduction to perl_control structures
Introduction to perl_control structuresIntroduction to perl_control structures
Introduction to perl_control structures
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
First steps in PERL
First steps in PERLFirst steps in PERL
First steps in PERL
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
newperl5
newperl5newperl5
newperl5
 

More from sana mateen

Files
FilesFiles
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
sana mateen
 
Php intro
Php introPhp intro
Php intro
sana mateen
 
Php and web forms
Php and web formsPhp and web forms
Php and web forms
sana mateen
 
Mail
MailMail
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
File upload php
File upload phpFile upload php
File upload php
sana mateen
 
Regex posix
Regex posixRegex posix
Regex posix
sana mateen
 
Encryption in php
Encryption in phpEncryption in php
Encryption in php
sana mateen
 
Authentication methods
Authentication methodsAuthentication methods
Authentication methods
sana mateen
 
Xml schema
Xml schemaXml schema
Xml schema
sana mateen
 
Xml dtd
Xml dtdXml dtd
Xml dtd
sana mateen
 
Xml dom
Xml domXml dom
Xml dom
sana mateen
 
Xhtml
XhtmlXhtml
Intro xml
Intro xmlIntro xml
Intro xml
sana mateen
 
Dom parser
Dom parserDom parser
Dom parser
sana mateen
 
Uses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perlUses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perl
sana mateen
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
sana mateen
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
sana mateen
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
sana mateen
 

More from sana mateen (20)

Files
FilesFiles
Files
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
 
Php intro
Php introPhp intro
Php intro
 
Php and web forms
Php and web formsPhp and web forms
Php and web forms
 
Mail
MailMail
Mail
 
Files in php
Files in phpFiles in php
Files in php
 
File upload php
File upload phpFile upload php
File upload php
 
Regex posix
Regex posixRegex posix
Regex posix
 
Encryption in php
Encryption in phpEncryption in php
Encryption in php
 
Authentication methods
Authentication methodsAuthentication methods
Authentication methods
 
Xml schema
Xml schemaXml schema
Xml schema
 
Xml dtd
Xml dtdXml dtd
Xml dtd
 
Xml dom
Xml domXml dom
Xml dom
 
Xhtml
XhtmlXhtml
Xhtml
 
Intro xml
Intro xmlIntro xml
Intro xml
 
Dom parser
Dom parserDom parser
Dom parser
 
Uses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perlUses for scripting languages,web scripting in perl
Uses for scripting languages,web scripting in perl
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
 

Recently uploaded

Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 

Recently uploaded (20)

Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 

Unit 1-array,lists and hashes

  • 1. ARRAYS, LISTS AND HASHES By SANA MATEEN
  • 2. ARRAYS  It is collections of scalar data items which have an assigned storage space in memory, and can therefore be accessed using a variable name.  The difference between arrays and hashes is that the constituent elements of an array are identified by a numerical index, which starts at zero for the first element.  array always starts with @, eg: @days_of_week.  An array stores a collection, and list is a collection, so it is natural to assign a list to an array. eg. @rainfall=(1.2, 0.4, 0.3, 0.1, 0, 0 , 0); This creates an array of seven elements. These can be accessed like $rainfall[0], $rainfall[1], .... $rainfall[6]. A list can also occur as elements of other list. @foo=(1,2,3, “string”); @foobar= (4, 5, @foo, 6); This gives foobar the value (4,5,1,2,3, “string”,6).
  • 3. MANIPULATING ARRAYS  Elements of an array are selected using C like square bracket syntax, eg: $bar=$foo[2].  The $ and [ ] make it clear that this instance foo is an element of the array foo, not the scalar variable foo.  A group of contiguous elements is called a slice, and is accessed using simple syntax.  @foo[1..3]  Is the same as the list ($foo[1],$foo[2],$foo[3])  The slice can be used as the destination of the assignment eg:@foo[1..3]= (“hop”, “skip”, “jump”);  Array variables and lists can be used interchangeably in almost any sensible situation: $front=(“bob”, “carol”, “ted”, “alice”)[0]; @rest=(“bob”, “carol”, “ted”, “alice”) [1..3]; or even @rest=qw/bob carol ted alice/[1..3]; Elements of an array can be selected by using another array selector.  @foo =(7, “fred”, 9);  @bar=(2,1,0); then @foo=@foo[@bar];
  • 4. LISTS  List is a collection of variables , constants or expressions which is to be treated as a whole . It is written as comma separated sequence of values. Eg: “red”, “green”, “blue”  A list often appears in a script enclosed in round brackets. (“red”, “green”, “blue”)  Short hand used in lists: (1..8) and (“A”.. “H”, “O”.. “Z”).  To save the tedious typing, qw(the quick brown fox)  Is short hand for : (“the”, “quick”, “brown”, “fox”).  qw- quote words operator, is an obvious extension of the q and qq operator.  qw/the quick brown fox/ (or) qw|the quick brown fox|  The list containing variables can appear as the target of an assignment and/or as the value to be assigned. ($a , $b , $c)= (1,2,3);
  • 5. MANIPULATING LISTS  Perl provides several built-in functions for list manipulation. Three useful ones are a)shift LIST b)unshift LIST c)push LIST  a) returns the first item of the list and moves remaining items down reducing the size of the list by 1.  b) the opposite of shift: puts the items in LIST at the beginning of ARRAY, moving the original contents up by the required amount.  c) push LIST: It is similar to unshift but adds the values in LIST to the end of ARRAY  ITERATING OVER LISTS Perl provides a number of mechanisms to achieve this. I. foreach II. map III. grep  foreach loop: It performs a simple iteration over all the elements of a list. foreach $item (list){ } This blocks takes each value from the list and repeats execution. foreach (@array){ .... #process $_
  • 6.  map: perl provides an inbuilt function map to create plural forms of words.  @p1=map $_. ‘s’ , @s;  general form of map is: map expression, list;  and map BLOCK list;  we can also use foreach loop to achieve the same. @s=qw/cat, dog, rabbit, hamster, rat/; @p1=(); foreach (@s){ push @p1, $_. ‘s’ }  grep : In unix grep is used to print all lines of the file which contains an instance of pattern. grep pattern file The perl grep function takes a pattern and a list and returns new list containing all the elements of the original list that match the pattern. Eg: @things = (car, bus, cardigan, jumper, carrot); grep /car/ @things returns the list (car,cardigan,carrot)
  • 7. HASHES  A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets.  Here is a simple example of using the hash variables −  #!/usr/bin/perl  %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);  print "$data{'John Paul'} = $data{'John Paul'}n";  print "$data{'Lisa'} = $data{'Lisa'}n";  print "$data{'Kumar'} = $data{'Kumar'}n";  This will produce the following result −  $data{'John Paul'} = 45  $data{'Lisa'} = 30  $data{'Kumar'} = 40  CREATING HASHES we can assign a list to an array, so it is not surprising that we can assign a list of key-value pairs to a hash. for example: %foo= (key1, value1, key2, value2,.....); alternative syntax is provided using the => operator to associate key-value pairs %foo =(banana => ‘yellow’ , apple=>’green’ , ...) Key Value(age) John Paul 45 Lisa 30 Kumar 40
  • 8. MANIPULATING HASHES  Perl provides a number of built-in functions to facilitate manipulation of hashes. If we have a hash called magic. keys %magic Returns a list of the keys of the elements in the hash. values %magic These functions provide way to iterate over the elements of hash using foreach: foreach $key(keys %magic) { do something with $magic($key) } Explicit loop variable is omitted, in which case the anonymous variable $_ will be assumed. foreach(keys %magic) { process $magic($_); } An alternative is to use “each” operator which delivers successive key-value pairs from a hash. while(($key,$value)=each %magic){ ... }
  • 9.  Other useful operators for manipulating hashes are delete and exists.  delete $magic($key)  Removes the elements whose key matches $key from the hash %magic, and  exists $magic($key)  Returns true if the hash %magic contains an element whose key matches $key.common idiomis exists($h{‘key’})&&do(statements) To avoid using an if statement.
  • 11. INTRODUCTION TO REGULAR EXPRESSIONS  It is a way of defining patterns.  A notation for describing the strings produced by regular expression.  The first application of regular expressions in computer system was in the text editors ed and sed in the UNIX system.  Perl provides very powerful and dynamic string manipulation based on the usage of regular expressions.  Pattern Match – searching for a specified pattern within string.  For example:  A sequence motif,  Accession number of a sequence,  Parse HTML,  Validating user input.  Regular Expression (regex) – how to make a pattern match.
  • 12. HOW REGEX WORK Regex code Perl compiler Input data (e.g. sequence file) outputregex engine
  • 13. SIMPLE PATTERNS  Place the regex between a pair of forward slashes ( / / ).  try:  #!/usr/bin/perl  while (<STDIN>) {  if (/abc/) {  print “>> found ‘abc’ in $_n”;  }  }  Save then run the program. Type something on the terminal then press return. Ctrl+C to exit script.  If you type anything containing ‘abc’ the print statement is returned.
  • 14. STAGES 1. The characters | ( ) [ { ^ $ * + ? . are meta characters with special meanings in regular expression. To use metacharacters in regular expression without a special meaning being attached, it must be escaped with a backslash. ] and } are also metacharacters in some circumstances. 2. Apart from meta characters any single character in a regular expression /cat/ matches the string cat. 3. The meta characters ^ and $ act as anchors: ^ -- matches the start of the line $ -- matches the end of the line. so regex /^cat/ matches the string cat only if it appears at the start of the line. /cat$/ matches only at the end of the line. /^cat$/ matches the line which contains the string cat and /^$/ matches an empty line. 4. The meta character dot (.) matches any single character except newline, so/c.t/ matches cat,cot,cut, etc.
  • 15. STAGES 5. A character class is set of characters enclosed in square brackets. Matches any single character from those listed. So /[aeiou]/- matches any vowel /[0123456789]/-matches any digit Or /[0-9]/ 6. A character class of the form /[^....]/ matches any characters except those listed, so /[^0-9]/ matches any non digit. 7. To remove the special meaning of minus to specify regular expression to match arithmetic operators. /[+-*/]/ 8. Repetition of characters in regular expression can be specified by the quantifiers * -- zero or more occurrences + -- one or more occurrences ? – zero or more occurrences 9. Thus /[0-9]+/ matches an unsigned decimal number and /a.*b/ matches a substring starting with ‘a’ and ending with ‘b’, with an indefinite number of other characters in between.
  • 16. FACILITIES 1. Alternations | If RE1,RE2,RE3 are regular expressions, RE1|RE2|RE3 will match any one of the components. 2. Grouping- ( ) Round Brackets can be used to group items. /pitt the (elder|younger)/ 3. Repetition counts Explicit repetition counts can be added to a component of regular expression /(wet[]){2}wet/ matches ‘ wet wet wet’ Full list of possible count modifiers are {n} – must occur exactly n times {n,} –must occur at least n times {n,m}- must occur at least n times but no more than m times. 4. Regular expression  Simple regex to check for an IP address:  ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$
  • 17. FACILITIES 5. Non-greedy matching A pattern including .* matches the longest string it can find. The pattern .*? Can be used when the shortest match is required. ? – shortest match 6.Short hand This notation is given for frequent occurring character classes. d – matches- digit w – matches – word s- matches- whitespace D- matches any non digit character Capitalization of notation reverses the sense 7. Anchors b – word boundary B – not a word boundary /bJohn/ -matches both the target string John and Johnathan. 8. Back References Round brackets define a series of partial matches that are remembered for use in subsequent processing or in the RegEx itself. 9. The Match Operator The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this: if ($bar =~ /foo/) Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator,
  • 18. BINDING OPERATOR  Previous example matched against $_  Want to match against a scalar variable?  Binding Operator “=~” matches pattern on right against string on left.  Usually add the m operator – clarity of code.  $string =~ m/pattern/
  • 19. MATCHING ONLY ONCE  There is also a simpler version of the match operator - 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.  For example, you can use this to get the first and last elements within a list:  To remember which portion of string matched we use $1,$2,$3 etc  #!/usr/bin/perl  @list = qw/food foosball subeo footnote terfoot canic footbrdige/;  foreach (@list) {  $first = $1 if ?(foo.*)?; $last = $1 if /(foo.*)/;  }  print "First: $first, Last: $lastn";  This will produce following result First: food, Last: footbrdige
  • 20. s/PATTERN/REPLACEMENT/; $string =~ s/dog/cat/; #/user/bin/perl $string = 'The cat sat on the mat'; $string =~ s/cat/dog/; print "Final Result is $stringn"; This will produce following result The dog sat on the mat THE SUBSTITUTION OPERATOR The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is: The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of .dog. with .cat. Using Another example:
  • 21. PATTERN MATCHING MODIFIERS  m//i – Ignore case when pattern matching.  m//g – Helps to count all occurrence of substring. $count=0; while($target =~ m/$substring/g) { $count++ }  m//m – treat a target string containing newline characters as multiple lines.  m//s –Treat a target string containing new line characters as single string, i.e dot matches any character including newline.  m//x – Ignore whitespace characters in the regular expression unless they occur in character class.  m//o – Compile regular expressions once only
  • 22. THE TRANSLATION OPERATOR  Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. 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, using the "The cat sat on the mat." string  #/user/bin/perl  $string = 'The cat sat on the mat';  $string =~ tr/a/o/;  print "$stringn";  When above program is executed, it produces the following result −  The cot sot on the mot.
  • 23. TRANSLATION OPERATOR MODIFIERS  Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value.  To change the case of the string, you might use the following syntax in place of the uc function.  $string =~ tr/a-z/A-Z/;  Following is the list of operators related to translation. Modifier Description c Complements SEARCHLIST d Deletes found but unreplaced characters s Squashes duplicate replaced characters.
  • 24. SPLIT  Syntax of split  split REGEX, STRING will split the STRING at every match of the REGEX.  split REGEX, STRING, LIMIT where LIMIT is a positive number. This will split the STRING at every match of the REGEX, but will stop after it found LIMIT- 1 matches. So the number of elements it returns will be LIMIT or less.  split REGEX - If STRING is not given, splitting the content of $_, the default variable of Perl at every match of the REGEX.  split without any parameter will split the content of $_ using /s+/ as REGEX.  Simple cases  split returns a list of strings:  use Data::Dumper qw(Dumper); # used to dump out the contents of any variable during the running of a program  my $str = "ab cd ef gh ij";  my @words = split / /, $str;  print Dumper @words;  The output is:  $VAR1 = [ 'ab', 'cd', 'ef', 'gh', 'ij' ];
  • 25.
  • 27. WHAT IS SUBROUTINE?  A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.  Perl uses the terms subroutine, method and function interchangeably.  The simplest way for reusing code is building subroutines.  They allow executing the same code in several places in your application, and they allow it to be executed with different parameters.  Define and Call a Subroutine  The general form of a subroutine definition in Perl programming language is as follows −  sub subroutine_name  { body of the subroutine  }  The typical way of calling that Perl subroutine is as follows −  subroutine_name( list of arguments );  Or  &subroutine_name(earlier way);
  • 28. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine.
  • 29. # # Main Code # pseudo-code ..set variables . call sub1 . call sub2 . call sub3 . exit program sub 1 # code for sub 1 exit subroutine sub 2 # code for sub 2 exit subroutine sub 3 # code for sub 3 call sub 4 exit subroutine sub 4 # code sub4 exit PROGRAM(CODE) DESIGN USING SUBROUTINES -PSEUDO CODE
  • 30. PASSING ARGUMENTS TO A SUBROUTINE  You can pass various arguments to a subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.  You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references to pass any array or hash.  Let's try the following example, which takes a list of numbers and then prints their average −
  • 31. PASSING LISTS TO SUBROUTINES  Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below −
  • 32. PASSING HASHES TO SUBROUTINES  When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs. For example −
  • 33. RETURNING VALUE FROM A SUBROUTINE  You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed will automatically returns value.  You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references to return any array or hash from a function.  Let's try the following example, which takes a list of numbers and then returns their average −
  • 34. PRIVATE VARIABLES IN A SUBROUTINE  By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator.  The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and evalstatements.  Following is an example showing you how to define a single or multiple private variables using my operator −  sub somefunc {  my $variable; # $variable is invisible outside somefunc()  my ($another, @an_array, %a_hash); # declaring many variables at once  }
  • 35. The following example distinguishes between global variable and private variable.
  • 36. ADVANTAGES OF SUBROUTINES  Saves typing → fewer lines of code →less likely to make a mistake  re-usable  if subroutine needs to be modified, can be changed in only one place  other programs can use the same subroutine  can be tested separately  makes the overall structure of the program clearer