Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.

Similar presentations


Presentation on theme: "Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size."— Presentation transcript:

1 Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size. You dont have to declare a maximum size: Perl automatically enlarges the array as needed during execution of the program.

2 Literal Lists A list is a set of elements enclosed within parentheses and separated by commas. String elements must be quoted. You can mix numerical and string values (1,3,5) is a list. So is (1, , duh). The empty list is (). Range operator: (1..5) creates a list (1, 2, 3, 4, 5). It adds in all elements from the left to the right by adding 1 to the previous value. The qw shortcut: If you want to enter a long list of strings, it is annoying to keep putting in all the quotes and commas. qw does this for you. Thus, qw(dog cat bird) is the same as (dog, cat, bird). This is a commonly used construction. Amusingly, you can use delimiters other than parentheses: qw! dog cat bird ! works just fine. Usually a bad idea, I suspect.

3 Array Variables Array variables start Arrays are treated differently from scalar variables. Assigning to an array. One way is to assign a = (1, 3, 5); You can also assign lists to each other this way: ($cat, $dog, $horse) = (1, 3, 5); Switching positions of 2 variables requires use of a third variable in C. In Perl: ($cat, $dog) = ($dog, $cat);

4 More of List Assignment If you have fewer elements on the left than on the right, the remaining elements on the right are ignored: ($dog, $cat) = qw(rover spot fido); causes $dog to have the value rover, and $cat to be spot. fido is simply not used. On the other hand, ($dog, $cat, $bird) = (rover, $spot); assigns names to $dog and $cat, but $bird keeps its initial value of undef. If an array variable is used on the left side of an assignment, it slurps up all remaining values on the right. ($dog, = qw( rover fido spot rex duke fluffy); gives names to $dog and gets al the rest: spot, rex, duke, and fluffy. But more subtly: $dog, $cat) = qw( rover fido spot rex duke fluffy); to get all the names, and $dog and $cat to remain undefined. And, $cat) = qw( rover fido spot rex duke fluffy); assigns rover to $dog and all the rest of the names $cat remains undef.

5 Printing an Array will print all elements of the array run together. (1, 3, 5); produces: 135. separates the elements with a space:

6 Accessing Array Elements Just as in C, array elements are in sequential order, starting with element 0, and they are accessed through array indices enclosed in square brackets. An array taken as a whole, is a plural object that for instance. However, individual array elements are scalars, and start with a $: $arr[0] is the first element $arr[1] is the second element, etc. $arr, without any index, is an entirely separate variable, having nothing whatsoever to do

7 More On Array Indices You can use a variable as an array index: $index = 3; print $arr[3]; print $arr[ $index ]; Gives the same result. Indices can be non-integers: they are simply truncated to the integer part when used as an index Negative numbers are used to access array elements from the end: $arr[-1] returns the last element in the array, $arr[-2] returns the next-to-last element, etc. $#arr gives the index of the last array element. Thus $arr[-1] == $arr[ $#arr ]; Very useful for loops.

8 Array Slices It is possible to access just part of an array, a slice of an array. For 4, 7, 9..12]; This creates the containing elements 0, 4, 7, 9, 10, 11, and 12 Note that a slice is itself is an array, and in front of it.

9 List Operators You can easily add or remove elements from either end of an array. push and pop operate on the end (right side) of an array. They treat the array as a stack. 7); adds the element 7 to the end of the array. $num = removes the last element (i.e. $arr[-1] ) and assigns it to $num. shift and unshift work on the beginning (left end) of the array. 9; puts the element 9 at the beginning of the array (i.e. $arr[0] ) and shifts all the other elements up one position. $num = removes the first array element and assigns it to $num. The other array elements move down one position in the array.

10 More List Operators reverse reverses the elements of an array. That is, it returns the elements in reverse order. You need to assign this functions reverse value to another array if you want to use = Or you can just assign it right back to the original = sort sorts the array. We will discuss this function in more depth later, but for now, there are 2 forms of sort that are useful: 1. sort in ASCII order (default for = 2. sort in numerical = sort {$a Quite a construction--be sure to copy it accurately when you use it. In particular, you must use $a and $b as indicated.

11 For Loops Perl uses two different constructions for loops. The first is the standard C style loop, a 3 part clause separated by semicolons: for ($i = 0; $i < 10; $i++) { do something; } The first part initializes the loop counter variable. The second part is a test: each time the program reaches the top of the loop, this clause is re-evaluated. If true, the loop is executed, and if false the program passes to the next statement. The third part changes the loop counter each time the loop finishes execution.

12 Foreach Perl has an alternate loop construction. For convenience the key word is foreach. However, the keyword for will also work for this type of loop. Sometimes called the indirect object form. foreach $element ) { do something; } each element is substituted into $element and the loop is executed, until all the array elements have been used. Note that you arent using array indices here at all, just the elements themselves. You can use the indices with a construction like: foreach $index ( 0.. $#arr) { something; } You can use a list instead of an array: foreach $pet ( cat, dog, bird) { }

13 $_, the Default Variable In many cases, if you dont assign input to a variable, Perl automatically assigns it to the variable $_, which can often be used without being written explicitly. while ( ) { print; } The input from STDIN is assigned to $_, and the $_ is printed, without ever being directly mentioned. Another major use is in foreach loops: foreach { print; } # prints roverspotfido foreach { print $_, ; } # prints rover spot fido Note that sometimes it is necessary (or merely useful) to write $_ into the code. Although it seems a small thing, use of $_is widespread in Perl, and saves a lot of time.

14 Scalar vs. List Context Here is one of the more subtle concepts in Perl, and you need to pay attention now. Some Perl expressions act differently depending on how they are used: their context. We have seen a small bit of this already: $var = 5 + 3; print $var; give 8 $var = 5. dog; print $var; gives 5dog. In the first case, 5 is treated as a numerical value, because you are adding a number to it. In the second case, 5 is treated as a string, because you are concatenating another string to it.

15 Scalar vs. List Context, p. 2 Arrays themselves can be used in scalar or list and both in list context. But what about: $var is being used in scalar context; it is being assigned to a scalar variable. In this case, the value returned is the number of elements in = (1, 3, 5, 7); gives ; but: $var print $var; gives 4 (the number of elements

16 Scalar vs. List Context, p. 3 Many functions usually produce a list. But, when used in scalar context (assigned to a scalar variable, for instance), they do something different. reverse is a good example of this. In list context, reverse returns the list in reverse order. In scalar context, reverse reverses a string (or reverses the result of concatenating the strings in a = reverse qw(dog cat bear); # gives bear, dog, cat $backwards = reverse qw(dog cat bear); # gives raebtacgod (Usually, reverse in scalar context is used on scalar strings: $backwards = reverse $sequence; ) Note that parentheses define a list context, and that some arrays are only 1 element long: $backwords = reverse rabbit; # gives tibbar ($backwards) = reverse rabbit; # gives rabbit, because reverse is used in list context on a 1 element array Some functions dont have a useful scalar context. For instance, using sort in a scalar context gives a value of undef.

17 Scalar vs. List Context, p. 4 A few miscellaneous things. Sometimes you need to force an array into scalar context. The keyword scalar does = (1, 3, 5, 7); # gives 1357 print # gives scalar print elements in array; # gives 4 elements in array in a list = ; Puts all the lines coming from STDIN into an array, one line per array element. Often used with file re-direction: on the command line test.pl < file.txt Can be used in tandem with chomp: = ); inputs all lines and removes the terminal \n from each of them.


Download ppt "Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size."

Similar presentations


Ads by Google