Lists and Arrays in Perl

Scalar represents “singular” in Perl. The “plural” are represented through Lists and Arrays

  • List is an ordered collection of scalars
  • Array is a variable that contains a list
  • Element of an array or list is a separate scalar variable

List is the data, array is the variable representing the list. There are no size limits imposed by Perl, so list can be as long as “max memory”.

  • Accessing Elements of an Array
$fred[0] = “yabba”;

$fred[0] .= “dabbadoo”;
  • Special Array Indices
$# indicates last element of an array

$rocks[0] = ‘bedrock’;

$rocks[90] = ‘limestone’; # rocks now has 90 elements, 1-89 are undef

$lastElementIndex = $#rocks;

$total = $lastElementIndex + 1;

$lastElement = $rocks[$#rocks]
  • List Literals
(1,2,3)

(1..5) # same as (1,2,3,4,5)

(0..$#rocks)

(“a”,”b”,”c”,”d”)
  • The qw Shortcut

o Shortcut makes it easy to generate list without typing a lot of extra quotes. Can also use it with custom delimiters

qw(a,b,c,d) # same as (“a”,”b”,”c”,”d”)

qw! Fred barney betty Wilma dino !

qw{ fred barney betty Wilma dino }
  • List Assignment
($a, $b, $c) = (“a”, “b”,”c”);

($a, $b, $c) = qw(a,b,c,d,e); # the d and e get silently ignored

($a, $b, $c) = qw(a,b); # $c gets value of undef
  • Array and the pop/push/shift/unshift/reverse operators
@rocks = qw(a,b,c,d,e);

@quarry = (@rocks,”f”,”g”); # value is a,b,c,d,e,f,g

$element = pop(@rocks); # element = g, rocks = a,b,c,d,e,f

pop @rocks; # rocks = a,b,c,d,e, - f is disregarded

push (@rocks, “f”); # rocks = a,b,c,d,e,f

$element = shift(@rocks); # element = a, rocks = b,c,d,e,f

unshift (@rocks, “a”); # rocks = a,b,c,d,e,f

@reversedArray = reverse @rocks # reversedArray = f,e,d,c,d,b,a

reverse @rocks # does nothing, reverse does not change original
  • The foreach Control
foreach $rock (qw(a,b,c) {

print “$rock \n”;

}
  • Perl default variable $_
foreach (1..10) {

print “$_ \n”;

}

$_ = “Hello World!\n”;

print;

 

 

Scalar vs List

Perl always expects a scalar or list value. Perl auto coverts data types based on context. Priority to the left of the expression (if left is scalar, then auto convert right to scalar).

42 + something # something should be scalar

Sort something # something should be list

@rocks = qw(a,b,c,d,e);

$size = 10 + @rocks; # 15

@backwards = reverse @rocks; # (e,d,c,b,a)

$backwards = reverse @rocks; # “edcba”

($element) = @rocks; # $element is still list, now nested in another list

$element = $rocks[0]; # $element is scalar, “a”

@fred = 6*7; # fred is single element list with 42

@betty = (); # an empty list

@betty = undef; # undef is scalar, so @betty is single element list with undef

print “Total “, scalar @rocks, “\n”; # scalar manually converts list to scalar

chomp(@lines = <STDIN>); # reads in lines as a list, and chomps