perl arrays and lists

24
Perl Arrays and Lists Software Tools

Upload: barton

Post on 14-Jan-2016

33 views

Category:

Documents


0 download

DESCRIPTION

Software Tools. Perl Arrays and Lists. 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: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Perl Arrays and Lists

Perl Arrays and Lists

Software Tools

Page 2: Perl Arrays and Lists

Slide 2

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.

Page 3: Perl Arrays and Lists

Slide 3

Lists

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

Page 4: Perl Arrays and Lists

Slide 4

Single-Word Lists

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

Page 5: Perl Arrays and Lists

Slide 5

Arrays

An array contains a list (zero or more scalar values). Array variable names are similar to scalar variable

names, except the initial character is “@” 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

Page 6: Perl Arrays and Lists

Slide 6

Inserting Arrays

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”.

Page 7: Perl Arrays and Lists

Slide 7

Left-Side Assignment

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.

Page 8: Perl Arrays and Lists

Slide 8

Array Length

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).

Page 9: Perl Arrays and Lists

Slide 9

Array Subscripting

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.

Page 10: Perl Arrays and Lists

Slide 10

Array Subscripting

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)

Page 11: Perl Arrays and Lists

Slide 11

Array Slices

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.

Page 12: Perl Arrays and Lists

Slide 12

List Slices

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

Page 13: Perl Arrays and Lists

Slide 13

Index Expressions

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

Page 14: Perl Arrays and Lists

Slide 14

Slice Expressions

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)

Page 15: Perl Arrays and Lists

Slide 15

Bad Subscripting

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.

Page 16: Perl Arrays and Lists

Slide 16

Backward Subscripting

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 3print $bill[$#bill]; # prints likespieprint $bill[$#bill-1]; # prints luckyprint $bill[-1]; # prints likespieprint $bill[-2]; # prints luckyprint $bill[-3]; # prints rich

Page 17: Perl Arrays and Lists

Slide 17

push and pop

You can use push and pop to 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)

pop returns undef if given an empty array.

Page 18: Perl Arrays and Lists

Slide 18

unshift and shift

You can use unshift and shift to 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)

shift returns undef if given an empty array.

Page 19: Perl Arrays and Lists

Slide 19

reverse and sort

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)

Page 20: Perl Arrays and Lists

Slide 20

Array Variable Interpolation

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 3

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

Page 21: Perl Arrays and Lists

Slide 21

Scalar and List Context

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)

Page 22: Perl Arrays and Lists

Slide 22

@ and $ Review

@ (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 [ ]

Page 23: Perl Arrays and Lists

Slide 23

Array chomp

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 contextchomp(@lines); # remove all trailing newlines

Page 24: Perl Arrays and Lists

Slide 24

Example: Max Value

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