2
Most read
3
Most read
5
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

PPTX
Scalar expressions and control structures in perl
PPTX
Perl names values and variables
PPTX
Strings,patterns and regular expressions in perl
PPTX
Query processing
PPTX
Unit 1-scalar expressions and control structures
PDF
Perl Scripting
PPTX
Methods in java
PDF
Java 8 Lambda Expressions
Scalar expressions and control structures in perl
Perl names values and variables
Strings,patterns and regular expressions in perl
Query processing
Unit 1-scalar expressions and control structures
Perl Scripting
Methods in java
Java 8 Lambda Expressions

What's hot (20)

ODP
Introduction to Perl - Day 1
PPTX
Regular expressions in Python
PPT
Java: GUI
PPS
Java Exception handling
PDF
Python Flow Control
PPT
Control Structures
PPTX
Multiple inheritance in c++
PDF
Java threads
PPTX
Inter Thread Communicationn.pptx
PPTX
Java program structure
PDF
Python functions
PPT
C operator and expression
PPT
Java operators
PPSX
Function in c
PPS
Wrapper class
PDF
JavaScript: Variables and Functions
PPTX
Java package
PPT
Java Networking
PPT
Control structures in C++ Programming Language
PPTX
Python: Modules and Packages
Introduction to Perl - Day 1
Regular expressions in Python
Java: GUI
Java Exception handling
Python Flow Control
Control Structures
Multiple inheritance in c++
Java threads
Inter Thread Communicationn.pptx
Java program structure
Python functions
C operator and expression
Java operators
Function in c
Wrapper class
JavaScript: Variables and Functions
Java package
Java Networking
Control structures in C++ Programming Language
Python: Modules and Packages
Ad

Viewers also liked (13)

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

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

PPTX
Unit 1-array,lists and hashes
PDF
Scripting3
PPTX
PERL PROGRAMMING LANGUAGE Basic Introduction
ODP
Introduction to Perl
PPT
Introduction to perl_control structures
PDF
Perl programming language
PPT
LPW: Beginners Perl
PPT
PERL.ppt
ODP
Beginning Perl
PPT
Introduction to perl scripting______.ppt
PPT
Perl Basics with Examples
ODP
Intermediate Perl
PDF
Marc’s (bio)perl course
PPT
Introduction to perl_lists
PPT
Crash Course in Perl – Perl tutorial for C programmers
PPT
Perl tutorial
ODP
Introduction to Perl - Day 2
PPT
Hashes Master
Unit 1-array,lists and hashes
Scripting3
PERL PROGRAMMING LANGUAGE Basic Introduction
Introduction to Perl
Introduction to perl_control structures
Perl programming language
LPW: Beginners Perl
PERL.ppt
Beginning Perl
Introduction to perl scripting______.ppt
Perl Basics with Examples
Intermediate Perl
Marc’s (bio)perl course
Introduction to perl_lists
Crash Course in Perl – Perl tutorial for C programmers
Perl tutorial
Introduction to Perl - Day 2
Hashes Master

More from sana mateen (20)

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

Recently uploaded (20)

PPTX
Unit IImachinemachinetoolopeartions.pptx
PPTX
SE unit 1.pptx aaahshdhajdviwhsiehebeiwheiebeiev
PDF
Engineering Solutions for Ethical Dilemmas in Healthcare (www.kiu.ac.ug)
PPTX
CS6006 - CLOUD COMPUTING - Module - 1.pptx
PPTX
22ME926Introduction to Business Intelligence and Analytics, Advanced Integrat...
PPT
UNIT-I Machine Learning Essentials for 2nd years
PPTX
Solar energy pdf of gitam songa hemant k
PPTX
SC Robotics Team Safety Training Presentation
PDF
Artificial Intelligence_ Basics .Artificial Intelligence_ Basics .
PDF
Lesson 3 .pdf
PPTX
SE unit 1.pptx by d.y.p.akurdi aaaaaaaaaaaa
PPT
Programmable Logic Controller PLC and Industrial Automation
PDF
Project_Mgmt_Institute_-Marc Marc Marc .pdf
PDF
Cryptography and Network Security-Module-I.pdf
PPTX
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
PDF
CELDAS DE COMBUSTIBLE TIPO MEMBRANA DE INTERCAMBIO PROTÓNICO.pdf
PPTX
Software-Development-Life-Cycle-SDLC.pptx
PDF
Performance, energy consumption and costs: a comparative analysis of automati...
PPTX
BBOC407 BIOLOGY FOR ENGINEERS (CS) - MODULE 1 PART 1.pptx
PDF
Software defined netwoks is useful to learn NFV and virtual Lans
Unit IImachinemachinetoolopeartions.pptx
SE unit 1.pptx aaahshdhajdviwhsiehebeiwheiebeiev
Engineering Solutions for Ethical Dilemmas in Healthcare (www.kiu.ac.ug)
CS6006 - CLOUD COMPUTING - Module - 1.pptx
22ME926Introduction to Business Intelligence and Analytics, Advanced Integrat...
UNIT-I Machine Learning Essentials for 2nd years
Solar energy pdf of gitam songa hemant k
SC Robotics Team Safety Training Presentation
Artificial Intelligence_ Basics .Artificial Intelligence_ Basics .
Lesson 3 .pdf
SE unit 1.pptx by d.y.p.akurdi aaaaaaaaaaaa
Programmable Logic Controller PLC and Industrial Automation
Project_Mgmt_Institute_-Marc Marc Marc .pdf
Cryptography and Network Security-Module-I.pdf
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
CELDAS DE COMBUSTIBLE TIPO MEMBRANA DE INTERCAMBIO PROTÓNICO.pdf
Software-Development-Life-Cycle-SDLC.pptx
Performance, energy consumption and costs: a comparative analysis of automati...
BBOC407 BIOLOGY FOR ENGINEERS (CS) - MODULE 1 PART 1.pptx
Software defined netwoks is useful to learn NFV and virtual Lans

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.