SlideShare a Scribd company logo
2
Most read
5
Most read
7
Most read
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.

More Related Content

What's hot (20)

PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PPT
Control Structures
Ghaffar Khan
 
PPTX
Subroutines in perl
sana mateen
 
PPTX
Strings,patterns and regular expressions in perl
sana mateen
 
PPT
Asp.net basic
Neelesh Shukla
 
PPTX
Error and exception in python
junnubabu
 
PDF
Print function in PHP
Vineet Kumar Saini
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PPTX
Php string function
Ravi Bhadauria
 
PPTX
Presentation on array
topu93
 
PPTX
Character generation techniques
Mani Kanth
 
PDF
Python tuple
Mohammed Sikander
 
PPTX
Strings in c++
Neeru Mittal
 
PDF
Set methods in python
deepalishinkar1
 
PPTX
Operating system
himanshu garg
 
PPTX
Introduction to java
Sandeep Rawat
 
PPTX
Control structures in java
VINOTH R
 
PDF
20160331_Automate the boring stuff with python
Sungman Jang
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Control Structures
Ghaffar Khan
 
Subroutines in perl
sana mateen
 
Strings,patterns and regular expressions in perl
sana mateen
 
Asp.net basic
Neelesh Shukla
 
Error and exception in python
junnubabu
 
Print function in PHP
Vineet Kumar Saini
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Php string function
Ravi Bhadauria
 
Presentation on array
topu93
 
Character generation techniques
Mani Kanth
 
Python tuple
Mohammed Sikander
 
Strings in c++
Neeru Mittal
 
Set methods in python
deepalishinkar1
 
Operating system
himanshu garg
 
Introduction to java
Sandeep Rawat
 
Control structures in java
VINOTH R
 
20160331_Automate the boring stuff with python
Sungman Jang
 

Viewers also liked (13)

PPTX
Lists, queues and stacks
andreeamolnar
 
PPTX
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PDF
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
widespreadpromotion
 
PPTX
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
15. STL - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
14. Files - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
Pointers in c++
Vineeta Garg
 
PPTX
12. Heaps - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPT
17. Trees and Graphs
Intro C# Book
 
Lists, queues and stacks
andreeamolnar
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
widespreadpromotion
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
15. STL - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
14. Files - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Pointers in c++
Vineeta Garg
 
12. Heaps - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
17. Trees and Graphs
Intro C# Book
 
Ad

Similar to Array,lists and hashes in perl (20)

PPTX
Unit 1-array,lists and hashes
sana mateen
 
PDF
Scripting3
Nao Dara
 
PPTX
PERL PROGRAMMING LANGUAGE Basic Introduction
johnboladevice
 
ODP
Introduction to Perl - Day 1
Dave Cross
 
ODP
Introduction to Perl
Dave Cross
 
PPT
Introduction to perl_control structures
Vamshi Santhapuri
 
PDF
Perl programming language
Elie Obeid
 
PPT
LPW: Beginners Perl
Dave Cross
 
PPT
PERL.ppt
Farmood Alam
 
ODP
Beginning Perl
Dave Cross
 
PPT
Introduction to perl scripting______.ppt
nalinisamineni
 
PPT
Perl Basics with Examples
Nithin Kumar Singani
 
ODP
Intermediate Perl
Dave Cross
 
PDF
Marc’s (bio)perl course
Marc Logghe
 
PPT
Introduction to perl_lists
Vamshi Santhapuri
 
PPT
Crash Course in Perl – Perl tutorial for C programmers
Gil Megidish
 
PPT
Perl tutorial
Manav Prasad
 
ODP
Introduction to Perl - Day 2
Dave Cross
 
Unit 1-array,lists and hashes
sana mateen
 
Scripting3
Nao Dara
 
PERL PROGRAMMING LANGUAGE Basic Introduction
johnboladevice
 
Introduction to Perl - Day 1
Dave Cross
 
Introduction to Perl
Dave Cross
 
Introduction to perl_control structures
Vamshi Santhapuri
 
Perl programming language
Elie Obeid
 
LPW: Beginners Perl
Dave Cross
 
PERL.ppt
Farmood Alam
 
Beginning Perl
Dave Cross
 
Introduction to perl scripting______.ppt
nalinisamineni
 
Perl Basics with Examples
Nithin Kumar Singani
 
Intermediate Perl
Dave Cross
 
Marc’s (bio)perl course
Marc Logghe
 
Introduction to perl_lists
Vamshi Santhapuri
 
Crash Course in Perl – Perl tutorial for C programmers
Gil Megidish
 
Perl tutorial
Manav Prasad
 
Introduction to Perl - Day 2
Dave Cross
 
Ad

More from sana mateen (20)

PPTX
Files
sana mateen
 
PPTX
PHP Variables and scopes
sana mateen
 
PPTX
Php intro
sana mateen
 
PPTX
Php and web forms
sana mateen
 
PPTX
Mail
sana mateen
 
PPTX
Files in php
sana mateen
 
PPTX
File upload php
sana mateen
 
PPTX
Regex posix
sana mateen
 
PPTX
Encryption in php
sana mateen
 
PPTX
Authentication methods
sana mateen
 
PPTX
Xml schema
sana mateen
 
PPTX
Xml dtd
sana mateen
 
PPTX
Xml dom
sana mateen
 
PPTX
Xhtml
sana mateen
 
PPTX
Intro xml
sana mateen
 
PPTX
Dom parser
sana mateen
 
PPTX
Unit 1-subroutines in perl
sana mateen
 
PPTX
Unit 1-uses for scripting languages,web scripting
sana mateen
 
PPTX
Unit 1-strings,patterns and regular expressions
sana mateen
 
PPTX
Unit 1-perl names values and variables
sana mateen
 
PHP Variables and scopes
sana mateen
 
Php intro
sana mateen
 
Php and web forms
sana mateen
 
Files in php
sana mateen
 
File upload php
sana mateen
 
Regex posix
sana mateen
 
Encryption in php
sana mateen
 
Authentication methods
sana mateen
 
Xml schema
sana mateen
 
Xml dtd
sana mateen
 
Xml dom
sana mateen
 
Intro xml
sana mateen
 
Dom parser
sana mateen
 
Unit 1-subroutines in perl
sana mateen
 
Unit 1-uses for scripting languages,web scripting
sana mateen
 
Unit 1-strings,patterns and regular expressions
sana mateen
 
Unit 1-perl names values and variables
sana mateen
 

Recently uploaded (20)

PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 

Array,lists and hashes in perl

  • 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.