SlideShare a Scribd company logo
1 of 26
Download to read offline
Perl Programming
                  Course
                 Lists and arrays




Krasimir Berov

 I-can.eu
Contents
1. What Is a List or Array?
2. Representation
   • Literals
   • Variables
3. Arrays interpolation
4. Adding and deleting elements
5. Operators and functions for lists and
  arrays
6. Arrays slicing
What Is a List or Array?
• A list is ordered scalar data
• An array is a variable that holds a list.
• Each element of the array is a separate
  scalar variable with an independent
  scalar value.
• Arrays can have any number of elements.
• The smallest array has no elements, while
  the largest array can fill all of available
  memory.
Literal Representation
• A list literal consists of comma-separated
  scalar values enclosed in parentheses.
  (1, 4.5, 15, 32 )   #list of four numeric values
  ('me', 'you', 'us') #list of three string values
  ('me',15,'you',32) #list of mixed values


• The elements of a list can be expressions
  (1, 4.5+15, $family=2 )#list of expressions:
                         #1, the result of 4.5+15
                         # and the value of $family
Literal Representation
• The empty list (no elements) is represented by an empty
  pair of parentheses
   () #empty list (zero elements)

• An item of the list literal can include the list constructor
  operator, indicated by two scalar values separated by
  two consecutive periods “..”.
• This operator creates a list of values starting at the left
  scalar value up through the right scalar value,
  incrementing by one each time.

   $, = $/; #$OUTPUT_FIELD_SEPARATOR is set to 'n'
   print (1..100);
Literal Representation
• qw/STRING/
  • Evaluates to a list of the words extracted out of
    STRING, using embedded whitespace as the
    word delimiters.
  • Generates a real list at compile time, and in
    scalar context it returns the last element in the
    list.
 $=$/; #$OUTPUT_RECORD_SEPARATOR is set to "n"
 $,=$/; #$OUTPUT_FIELD_SEPARATOR is set to "n"
 print qw{me you us};
 print ('me', 'you', 'us'); # the same as above
 $me = qw(me you us);
 print $me;                 # prints 'us'
Variables
• An array variable holds a single list literal
  (zero or more scalar values).
• The value of an array variable that has not
  yet been assigned is (), the empty list.
• Entire arrays (and slices of arrays and
  hashes) are denoted by '@'.
• The length of an array is not pre-declared.
  Perl autovivifies whatever space it needs.
Variables
• Example
 $, = $ =$/;
 my @numbers = (1, 4.5, 15, 32 );
 my @family = ('me', 'you', 'us');
 print @family,$/;
 $family[3] = 'he';
 print @family,$/;
 my @things = (@numbers, @family);#flattened
 my @predators = qw/leopard tiger panther/;
 my @slices = (1..3, A..D);
 print $/;
 print @numbers,@family,@things,@slices,@predators;
Arrays interpolation
• Arrays may be interpolated the same way
  as scalars into double quoted strings.
• Arrays' elements are scalars and can be
  interpolated too.
  $ = $/;
  my @numbers = (1, 4.5, 15, 32 );
  my @family = ('me', 'you', 'us');

  print   "Do $family[1] have $numbers[2] leva?";
  print   "Sorry, I do have $family[0] only.";
  $"=',   ';#$LIST_SEPARATOR
  print   "O... @family... who cares!";
Adding and deleting elements
• operators:
  • push
  • pop
  • shift
  • unshift
  • splice
Adding and deleting elements
• push ARRAY,LIST
  • Treats ARRAY as a stack, and pushes the values of
    LIST onto the end of ARRAY.
  • The length of ARRAY increases by the length of LIST.

  • Returns the number of elements in the array
    following the completed push.
  use Data::Dumper;
  $ =$/;
  my @family = qw ( me you us );
  print scalar @family;#get the number of elements
  print push(@family, qw ( him her ));
  print Dumper @family;
Adding and deleting elements
• pop ARRAY
  pop
  • Pops and returns the last value of the array,
    shortening the array by one element.
  • If there are no elements in the array, returns the
    undefined value (although this may happen at other
    times as well).
  • If ARRAY is omitted, pops the @ARGV array in the
    main program, and the @_ array in subroutines, just
    like shift.
  use Data::Dumper;
  $ =$/;
  my @names = qw ( Цвети Бети Пешо );
  my $last_name = pop(@names);
  warn "popped = $last_name";
  print Dumper @names;
Adding and deleting elements
• shift ARRAY
  shift
   • Shifts the first value of the array off and returns it,
     shortening the array by 1 and moving everything
     down.
   • If there are no elements in the array, returns the
     undefined value.
   • If ARRAY is omitted, shifts the @_ array within the
     lexical scope of subroutines and formats, and the
     @ARGV array outside of a subroutine...
   use Data::Dumper;$ =$/;
   my @names = qw ( Цвети Бети Пешо );
   my $last_name = shift(@names);
   warn "shifted = $last_name";
   print Dumper @names;
Adding and deleting elements
• unshift ARRAY,LIST
  • Does the opposite of a shift. Or the opposite of a
    push, depending on how you look at it.
  • Prepends LIST to the front of the array, and returns
    the new number of elements in the array.
  • Note the LIST is prepended whole, not one element
    at a time, so the prepended elements stay in the
    same order.
  use Data::Dumper; $ =$/;
  my @names = qw ( Цвети Бети Пешо );
  print 'elements:', scalar @names;
  print 'elements:', unshift(@names,qw/Део Иво/);
  print Dumper @names;
Adding and deleting elements
• splice ARRAY,OFFSET,LENGTH,LIST
  • Removes the elements designated by OFFSET and
    LENGTH from an array, and replaces them with the
    elements of LIST, if any.
  • In list context, returns the elements removed from
    the array.
  • In scalar context, returns the last element removed,
    or undef if no elements are removed.
  • The array grows or shrinks as necessary.

  my @words = qw ( hello there );
  splice(@words, 1, 0, 'out');
  print join(" ", @words);
Operators and functions for lists
     and arrays
• foreach
• join
• map
• grep
Operators and functions for lists
     and arrays
• foreach (@array)
  • Use foreach to iterate through all the elements of a list. Its
    formal definition is:
    LABEL foreach VAR (LIST) BLOCK
    This is a control flow structure.
  • The foreach structure supports last, next, and redo
    statements. Use a simple foreach loop to do something to
    each element in an array.
  • DO NOT ADD OR DELETE ELEMENTS TO AN ARRAY
    BEING PROCESSED IN A FOREACH LOOP.
  my @fruits = qw ( apples oranges lemons pears );
  foreach my $fruit (@fruits) {
      print "fruit is '$fruit'n";
  }
Operators and functions for lists
       and arrays
• join EXPR,LIST
  • Joins the separate strings of LIST into a
    single string with fields separated by the
    value of EXPR, and returns that new
    string.


  my @fields = qw ( id name position );
  my $SQL = 'SELECT '
      . join(", ", @fields)
      . ' from empoyees';
  print $SQL;
Operators and functions for lists
    and arrays
• map BLOCK LIST
  map EXPR,LIST
 • Evaluates the BLOCK or EXPR for each element of
   LIST (locally setting $_ to each element) and returns
   the list value composed of the results of each such
   evaluation.
 • In scalar context, returns the total number of
   elements so generated.
 • In list context evaluates BLOCK or EXPR, so each
   element of LIST may produce zero, one, or more
   elements in the returned value.
 • Note that $_ is an alias to the list value, so it can be
   used to modify the elements of the LIST. See
   perlfunc/map.
Operators and functions for
    lists and arrays
• map Example:


  my @nums = (0x410 .. 0x44f);
  my @chars = map(chr , @nums);
  print @chars;

  print '-' x 20;
  my @names = qw(Цвети Пешо Иван);
  my @mapped = map {$_ if $_ eq 'Пешо'} @names;
  print @mapped;
Operators and functions for lists
     and arrays
• grep BLOCK LIST
  grep EXPR,LIST
  • Evaluates the BLOCK or EXPR for each element of
    LIST (locally setting $_ to each element) and returns
    the list value consisting of those elements for which
    the expression evaluated to true.
  • In scalar context, returns the number of times the
    expression was true.
  • Note that $_ is an alias to the list value, so it can be
    used to modify the elements of the LIST.
  • See perlfunc/grep.
Operators and functions for lists
    and arrays
• grep Example:

  my @nums = (0x410 .. 0x44f);
  my @chars = grep(
              ($_ >= 0x410 and $_ < 0x430), @nums
              );
  map($_ = chr, @chars);#modify inplace $_
  print @chars;

  #grep for 'а'
  if( my $times = grep    { chr($_) =~ /а/i } @nums ){
       print "'а' codes   found:
    $times times in the   list."
  }
Arrays slicing
• Range Operator (..)
  • In list context, it returns a list of values counting (up
    by ones) from the left value to the right value.
  • If the left value is greater than the right value then it
    returns the empty list.
  • The range operator is useful for writing
    foreach (1..10) loops and for doing slice
    operations on arrays.
  • No temporary array is created when the range
    operator is used as the expression in foreach loops.
  • See: perlop/Range Operators, perldata/Slices
Arrays slicing
• Range Operator (..)
• Example
  my @nums = (0x410 .. 0x44f);
  print chr($nums[$_]) foreach(0..14);
  #print a slice
  print @nums[0..14],$/;
  #print a character map table from slice
  print ' dec | hex | char', '-' x 19;
  print map {
      $_.' | '
      . sprintf('0x%x',$_).' | '.chr($_)
      . "n" . '-' x 19
  } @nums[0..14];
Lists and arrays




Questions?
Exercices
• TODO

More Related Content

What's hot

Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
Utkarsh Sengar
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 

What's hot (19)

Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
Scripting3
Scripting3Scripting3
Scripting3
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 

Similar to Lists and arrays

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Crash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersCrash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmers
Gil Megidish
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
clearvisioneyecareno
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
info335653
 

Similar to Lists and arrays (20)

Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Introduction to perl_control structures
Introduction to perl_control structuresIntroduction to perl_control structures
Introduction to perl_control structures
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
Arrays
ArraysArrays
Arrays
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perl
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Crash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersCrash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmers
 
Data Structure
Data StructureData Structure
Data Structure
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 
9
99
9
 
ACP-arrays.pptx
ACP-arrays.pptxACP-arrays.pptx
ACP-arrays.pptx
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
 

More from Krasimir Berov (Красимир Беров)

More from Krasimir Berov (Красимир Беров) (11)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Network programming
Network programmingNetwork programming
Network programming
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

Lists and arrays

  • 1. Perl Programming Course Lists and arrays Krasimir Berov I-can.eu
  • 2. Contents 1. What Is a List or Array? 2. Representation • Literals • Variables 3. Arrays interpolation 4. Adding and deleting elements 5. Operators and functions for lists and arrays 6. Arrays slicing
  • 3. What Is a List or Array? • A list is ordered scalar data • An array is a variable that holds a list. • Each element of the array is a separate scalar variable with an independent scalar value. • Arrays can have any number of elements. • The smallest array has no elements, while the largest array can fill all of available memory.
  • 4. Literal Representation • A list literal consists of comma-separated scalar values enclosed in parentheses. (1, 4.5, 15, 32 ) #list of four numeric values ('me', 'you', 'us') #list of three string values ('me',15,'you',32) #list of mixed values • The elements of a list can be expressions (1, 4.5+15, $family=2 )#list of expressions: #1, the result of 4.5+15 # and the value of $family
  • 5. Literal Representation • The empty list (no elements) is represented by an empty pair of parentheses () #empty list (zero elements) • An item of the list literal can include the list constructor operator, indicated by two scalar values separated by two consecutive periods “..”. • This operator creates a list of values starting at the left scalar value up through the right scalar value, incrementing by one each time. $, = $/; #$OUTPUT_FIELD_SEPARATOR is set to 'n' print (1..100);
  • 6. Literal Representation • qw/STRING/ • Evaluates to a list of the words extracted out of STRING, using embedded whitespace as the word delimiters. • Generates a real list at compile time, and in scalar context it returns the last element in the list. $=$/; #$OUTPUT_RECORD_SEPARATOR is set to "n" $,=$/; #$OUTPUT_FIELD_SEPARATOR is set to "n" print qw{me you us}; print ('me', 'you', 'us'); # the same as above $me = qw(me you us); print $me; # prints 'us'
  • 7. Variables • An array variable holds a single list literal (zero or more scalar values). • The value of an array variable that has not yet been assigned is (), the empty list. • Entire arrays (and slices of arrays and hashes) are denoted by '@'. • The length of an array is not pre-declared. Perl autovivifies whatever space it needs.
  • 8. Variables • Example $, = $ =$/; my @numbers = (1, 4.5, 15, 32 ); my @family = ('me', 'you', 'us'); print @family,$/; $family[3] = 'he'; print @family,$/; my @things = (@numbers, @family);#flattened my @predators = qw/leopard tiger panther/; my @slices = (1..3, A..D); print $/; print @numbers,@family,@things,@slices,@predators;
  • 9. Arrays interpolation • Arrays may be interpolated the same way as scalars into double quoted strings. • Arrays' elements are scalars and can be interpolated too. $ = $/; my @numbers = (1, 4.5, 15, 32 ); my @family = ('me', 'you', 'us'); print "Do $family[1] have $numbers[2] leva?"; print "Sorry, I do have $family[0] only."; $"=', ';#$LIST_SEPARATOR print "O... @family... who cares!";
  • 10. Adding and deleting elements • operators: • push • pop • shift • unshift • splice
  • 11. Adding and deleting elements • push ARRAY,LIST • Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY. • The length of ARRAY increases by the length of LIST. • Returns the number of elements in the array following the completed push. use Data::Dumper; $ =$/; my @family = qw ( me you us ); print scalar @family;#get the number of elements print push(@family, qw ( him her )); print Dumper @family;
  • 12. Adding and deleting elements • pop ARRAY pop • Pops and returns the last value of the array, shortening the array by one element. • If there are no elements in the array, returns the undefined value (although this may happen at other times as well). • If ARRAY is omitted, pops the @ARGV array in the main program, and the @_ array in subroutines, just like shift. use Data::Dumper; $ =$/; my @names = qw ( Цвети Бети Пешо ); my $last_name = pop(@names); warn "popped = $last_name"; print Dumper @names;
  • 13. Adding and deleting elements • shift ARRAY shift • Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. • If there are no elements in the array, returns the undefined value. • If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside of a subroutine... use Data::Dumper;$ =$/; my @names = qw ( Цвети Бети Пешо ); my $last_name = shift(@names); warn "shifted = $last_name"; print Dumper @names;
  • 14. Adding and deleting elements • unshift ARRAY,LIST • Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. • Prepends LIST to the front of the array, and returns the new number of elements in the array. • Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. use Data::Dumper; $ =$/; my @names = qw ( Цвети Бети Пешо ); print 'elements:', scalar @names; print 'elements:', unshift(@names,qw/Део Иво/); print Dumper @names;
  • 15. Adding and deleting elements • splice ARRAY,OFFSET,LENGTH,LIST • Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. • In list context, returns the elements removed from the array. • In scalar context, returns the last element removed, or undef if no elements are removed. • The array grows or shrinks as necessary. my @words = qw ( hello there ); splice(@words, 1, 0, 'out'); print join(" ", @words);
  • 16. Operators and functions for lists and arrays • foreach • join • map • grep
  • 17. Operators and functions for lists and arrays • foreach (@array) • Use foreach to iterate through all the elements of a list. Its formal definition is: LABEL foreach VAR (LIST) BLOCK This is a control flow structure. • The foreach structure supports last, next, and redo statements. Use a simple foreach loop to do something to each element in an array. • DO NOT ADD OR DELETE ELEMENTS TO AN ARRAY BEING PROCESSED IN A FOREACH LOOP. my @fruits = qw ( apples oranges lemons pears ); foreach my $fruit (@fruits) { print "fruit is '$fruit'n"; }
  • 18. Operators and functions for lists and arrays • join EXPR,LIST • Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string. my @fields = qw ( id name position ); my $SQL = 'SELECT ' . join(", ", @fields) . ' from empoyees'; print $SQL;
  • 19. Operators and functions for lists and arrays • map BLOCK LIST map EXPR,LIST • Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value composed of the results of each such evaluation. • In scalar context, returns the total number of elements so generated. • In list context evaluates BLOCK or EXPR, so each element of LIST may produce zero, one, or more elements in the returned value. • Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. See perlfunc/map.
  • 20. Operators and functions for lists and arrays • map Example: my @nums = (0x410 .. 0x44f); my @chars = map(chr , @nums); print @chars; print '-' x 20; my @names = qw(Цвети Пешо Иван); my @mapped = map {$_ if $_ eq 'Пешо'} @names; print @mapped;
  • 21. Operators and functions for lists and arrays • grep BLOCK LIST grep EXPR,LIST • Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. • In scalar context, returns the number of times the expression was true. • Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. • See perlfunc/grep.
  • 22. Operators and functions for lists and arrays • grep Example: my @nums = (0x410 .. 0x44f); my @chars = grep( ($_ >= 0x410 and $_ < 0x430), @nums ); map($_ = chr, @chars);#modify inplace $_ print @chars; #grep for 'а' if( my $times = grep { chr($_) =~ /а/i } @nums ){ print "'а' codes found: $times times in the list." }
  • 23. Arrays slicing • Range Operator (..) • In list context, it returns a list of values counting (up by ones) from the left value to the right value. • If the left value is greater than the right value then it returns the empty list. • The range operator is useful for writing foreach (1..10) loops and for doing slice operations on arrays. • No temporary array is created when the range operator is used as the expression in foreach loops. • See: perlop/Range Operators, perldata/Slices
  • 24. Arrays slicing • Range Operator (..) • Example my @nums = (0x410 .. 0x44f); print chr($nums[$_]) foreach(0..14); #print a slice print @nums[0..14],$/; #print a character map table from slice print ' dec | hex | char', '-' x 19; print map { $_.' | ' . sprintf('0x%x',$_).' | '.chr($_) . "n" . '-' x 19 } @nums[0..14];