- 52 Views
- Uploaded on
- Presentation posted in: General

Perl Arrays and Lists

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Software Tools

Perl Arrays and Lists

- A list is an ordered collection of scalar data.
- A list begins and ends with parentheses, with the elements separated by commas (and optional spaces).
(1,2, 3,4.1)

- List elements can be constants or expressions:
("Bill", 4, "pie", "B. Gates")

($num, 17, $num+1+$i)

- Memory for lists is dynamically allocated and removed as the program runs.

- The empty list (no elements) is represented by an empty pair of parenthesis:
( )# empty list

- The list constructor “..” creates a list of values with increments of 1:
(1 .. 4) # same as (1, 2, 3, 4)

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

(1.2 .. 5.7) # same as (1, 2, 3, 4, 5) ??!!

(1, 5 .. 7) # same as (1, 5, 6, 7)

($min .. $max) # depends on values of $min and $max

(10 .. 5) # same as ( ) -> it can’t count down

- There is a shortcut for lists of single-word strings, the “quote word” function:
("bill", "gates", "pie", "toss") # usual version

qw(bill gates pie toss) # same as above

qw(bill

gates

pie

toss) # also okay

- An array contains a list (zero or more scalar values).
- Array variable names are similar to scalar variable names, except the initial character is [email protected] instead of “$”.
@numbers = (1,2, 3,4.1);

@all = @numbers;# copies array to @all

@list1 = ("Bill", 4, "pie", "B. Gates");

$num = 2;

@group = ($num, 17, $num+1);

- If a scalar value is assigned to an array variable, it becomes a single-element list automatically:
@a = 4;# becomes (4) automatically

- You can also insert array elements into lists:
@numbers = (6,7,8);

@numbers = (1, 2, @numbers, 10); # (1,2,6,7,8,10)

@numbers = (0, @numbers); # (0,1,2,6,7,8,10)

@numbers = (@numbers, 99); # (0,1,2,6,7,8,10,99)

- Note that the inserted array elements are at the same level as the other elements, not in a “sub-list”.

- If a list only contains variables, you can use it on the left side of an assignment:
($a,$b,$c) = (1,2,3); # set $a=1, $b=2, $c=3

($a,$b) = ($b,$a); # swap $a and $b

($d,@bill) = ($a,$b,$c); # set $d=$a and @bill=($b,$c)

($e,@bill) = @bill; # remove first element of @bill

# and put it in $e

# end up with: $a=2, $b=1, $c=3

# $d=2, $e=1, @bill=(3)

- An array variable can only occur in the last position in the list, because the array variable is “greedy” and consumes all the remaining values.

- If an array variable is assigned to a scalar variable, the number assigned is the length of the array:
@nums = (1,2,3);

$n = @nums; # $n gets 3, the length of @nums

- The context determines whether the length of the array is used or the list:
$n = @nums;# $n gets the length of @nums

($n) = @nums; # $n gets the first element of @nums

- The first assignment is a scalar assignment, so @nums is treated as a scalar, returning its length.
- The second assignment is an array assignment, and gives the first element of @nums (silently discarding the rest).

- Each element of an array can be accessed by its integer position in the list.
- The first element starts at position 0 (like C++ arrays).
- The first element of the @a array is accessed as $a[0]:
@a = qw(bill gates pie toss);

$name1 = $a[0]; # sets name1 to "bill"

$name2 = $a[3]; # sets name2 to "toss"

$a[1] = "clinton"; # a: qw(bill clinton pie toss)

- Note that the @ on the array name becomes a $ when accessing individual elements.

- You can use all the usual scalar operations on the array elements:
@a = (1,2,3);

$a[0]++;# a: (2,2,3)

$a[1] += 4;# a: (2,6,3)

$a[2] += $a[0];# a: (2,6,5)

# swap the first two elements

($a[0],$a[1]) = ($a[1],$a[0]); # a: (6,2,5)

- Accessing a list of elements from the same array is called a slice.
- Perl provides a special shortcut for slices:
@a = (1,2,3);

@a[0,1] = @a[1,0]; # swap the first two elements

@a[0,1,2] = @a[1,1,1]; # make all 3 elements like the 2nd

@a[1,2] = (7,4); # change the last two to 7 and 4

# a: (1,7,4)

- Note that slices use @ rather than $. This is because slices work with lists rather than scalar values.

- Slices also work directly on lists:
$c = (1,2,3,4,5)[2];# sets $c to 3

@b = (1,2,3,4,5)[2,4];# sets @b to (3,5)

- The second statement above is equivalent to:
@x = (1,2,3,4,5);

@b = @x[2,4];

- The second statement above is equivalent to:

- You can use expressions for the subscripts just like in C++:
@list1 = (5,6,7);

$n = 2;

$m = $list1[$n];# $m = 7

$p = $list1[$n-1];# $p = 6

($p) = (5,6,7)[$n-1];# same thing using slice

- You can use also array expressions to index slices if you want to be tricky:
@nums = (5,6,7);

@i = (2,1,0);

@rev = @nums[@i];

# same as @nums[2,1,0]

# or ($nums[2], $nums[1], $nums[0])

# or (7,6,5)

- If you access an array beyond the end of the array, the undef value is returned without warning.
- undef is 0 when used as a number, the empty string when used as a string.
@nums = (5,6,7);

$nums[3] = "bill"; # @nums: (5,6,7,"bill")

$nums[5] = "g."; # @nums: (5,6,7,"bill",undef,"g.")

- Assignment to an array element with a subscript less than zero is a fatal error.

- You can use $#bill to get the index value of the last element of @bill.
- Accessing an array with a negative subscript counts back from the end. So, another way to get the last element of @bill is $bill[-1].
@bill = qw(cheap rich lucky likespie);

print $#bill;# prints 3

print $bill[$#bill];# prints likespie

print $bill[$#bill-1];# prints lucky

print $bill[-1];# prints likespie

print $bill[-2];# prints lucky

print $bill[-3];# prints rich

- You can use push and popto add and remove values from the end of an array.
@a = (1,2,3);

$new = 6;

push(@a,$new); # same as @a = (@a,$new)

# so far: (1,2,3,6)

$oldvalue = pop(@a); # removes last element of @a

# so far: (1,2,3)

push(@a,4,5,6); # can push multiple values

# so far: (1,2,3,4,5,6)

- popreturns undef if given an empty array.

- You can use unshift and shiftto add and remove values from the beginning of an array.
@a = (1,2,3);

$new = 6;

unshift(@a,$new); # same as @a = ($new, @a)

# so far: (6,1,2,3)

$old = shift(@a); # removes first element of @a

# so far: (1,2,3)

unshift(@a,4,5,6); # can unshift multiple values

# same as @a = (4,5,6,@a)

# so far: (4,5,6,1,2,3)

- shiftreturns undef if given an empty array.

- The reverse function reverses the array, returning the resulting list:
@a = (1,2,3);

@b = reverse(@a);# @b=(3,2,1), @a unchanged

@b = reverse(1,2,3);# same thing

@b = reverse(@b);# @b=(1,2,3)

- The sort function returns a sorted array in ascending ASCII order:
@size = qw(small medium large);

@sortsize = sort(@size); # large, medium, small

@sortsize = sort(qw(small medium large)); # same

@a = (1,2,4,8,16,32,64);

@b = sort(@a);# @b=(1,16,2,32,4,64,8)

- Array elements can be interpolated in double-quoted strings:
@comp111 = qw(unix shell perl);

print "$comp111[0] programming is mainly done ";

print "in $comp111[2]\n";

$n=3;

print "$comp111[0] programming is mainly done ";

print "in $comp111[$n-1]\n";# same thing

- Arrays and array slices will be interpolated (printed) with spaces between the elements:
@a = (1,2,"bill",3);

print "a: @a\n";# prints a: 1 2 bill 3print "a1: @a[1,2]\n";# prints a1: 2 bill

- If an operator or function expects a scalar argument, the argument is evaluated in a scalar context.
$n = @nums;# $n gets the length of @nums

- If an operator or function expects a list argument, the argument is evaluated in a list context.
($n) = @nums; # $n gets the first element of @nums

- A scalar value used within a list context is promoted to a single-element array.
@nums = 1; # @nums = (1)

@ (at sign)

Refers to the entire array

or slice of an array (when used with [ ]).

$ (dollar sign)

Refers to one element of the array, used with [ ]

- The chomp function also works for array variables, removing any ending newlines in each element :
@comp111 = qw(unix\n shell\n perl);

chomp(@comp111);

# @comp111 is now qw(unix shell perl)

- Array chomp is especially useful when reading a file or input from a user.
- <STDIN> in a list context will return all remaining lines up to the end of the file, or until the user hits CTRL-D.
@lines = <STDIN>;# read input in a list context

chomp(@lines);# remove all trailing newlines

- How to find the biggest value in an array of numbers @a:
@a = (23,4,56,99,36,24);

$max = $a[0];

for($i=1; $i<@a; $i++){

if($a[$i] > $max){

$max = $a[$i];

}

}

print "max is: $max\n";