This is the third set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
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);
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];