SlideShare a Scribd company logo
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

PDF
Working with text, Regular expressions
PDF
Perl Scripting
PPT
Class 5 - PHP Strings
ODP
Introduction to Perl - Day 1

What's hot (19)

PDF
Scripting3
PPT
Perl Presentation
PDF
Perl 5.10 for People Who Aren't Totally Insane
PDF
Perl programming language
ODP
Introduction to Perl - Day 2
PPTX
PHP Functions & Arrays
PPTX
Bioinformatics p1-perl-introduction v2013
PDF
DBIx::Class introduction - 2010
PPT
Class 4 - PHP Arrays
PDF
Marc’s (bio)perl course
PDF
Sorting arrays in PHP
PPT
Perl 101 - The Basics of Perl Programming
PDF
Introduction to Perl and BioPerl
ODP
perl usage at database applications
PPT
LPW: Beginners Perl
PDF
Improving Dev Assistant
PPTX
PHP Strings and Patterns
Scripting3
Perl Presentation
Perl 5.10 for People Who Aren't Totally Insane
Perl programming language
Introduction to Perl - Day 2
PHP Functions & Arrays
Bioinformatics p1-perl-introduction v2013
DBIx::Class introduction - 2010
Class 4 - PHP Arrays
Marc’s (bio)perl course
Sorting arrays in PHP
Perl 101 - The Basics of Perl Programming
Introduction to Perl and BioPerl
perl usage at database applications
LPW: Beginners Perl
Improving Dev Assistant
PHP Strings and Patterns
Ad

Similar to Lists and arrays (20)

PPTX
Unit 1-array,lists and hashes
PPT
Introduction to perl_control structures
PPT
Introduction to perl_lists
PPTX
Array,lists and hashes in perl
PPTX
PHP array 1
PDF
List , tuples, dictionaries and regular expressions in python
PPTX
11 Introduction to lists.pptx
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
PPTX
UNIT IV (4).pptx
PPT
Crash Course in Perl – Perl tutorial for C programmers
PPTX
Data Structure
PPTX
Marcs (bio)perl course
PPTX
PERL PROGRAMMING LANGUAGE Basic Introduction
PDF
you will implement some sorting algorithms for arrays and linked lis.pdf
PDF
you will implement some sorting algorithms for arrays and linked lis.pdf
DOC
PPTX
ACP-arrays.pptx
PDF
DSA UNIT II ARRAY AND LIST - notes
PDF
Perl_Tutorial_v1
Unit 1-array,lists and hashes
Introduction to perl_control structures
Introduction to perl_lists
Array,lists and hashes in perl
PHP array 1
List , tuples, dictionaries and regular expressions in python
11 Introduction to lists.pptx
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
UNIT IV (4).pptx
Crash Course in Perl – Perl tutorial for C programmers
Data Structure
Marcs (bio)perl course
PERL PROGRAMMING LANGUAGE Basic Introduction
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
ACP-arrays.pptx
DSA UNIT II ARRAY AND LIST - notes
Perl_Tutorial_v1
Ad

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

Recently uploaded (20)

PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
How to Build Crypto Derivative Exchanges from Scratch.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
KodekX | Application Modernization Development
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
Transforming Manufacturing operations through Intelligent Integrations
madgavkar20181017ppt McKinsey Presentation.pdf
How to Build Crypto Derivative Exchanges from Scratch.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Reimagining Insurance: Connected Data for Confident Decisions.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Event Presentation Google Cloud Next Extended 2025
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
NewMind AI Monthly Chronicles - July 2025
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Chapter 2 Digital Image Fundamentals.pdf
KodekX | Application Modernization Development
Belt and Road Supply Chain Finance Blockchain Solution
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Top Generative AI Tools for Patent Drafting in 2025.pdf
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT

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];