5.3 Array Functions
Arrays can grow and shrink. The Perl array functions allow you to insert or delete elements of the array from the front, middle, or end of the list, to sort arrays, perform calculations on elements, to search for patterns, and more.
5.3.1 Adding Elements to an Array
The push Function.
The push function pushes values onto the end of an array, thereby increasing the length of the array (see Figure 5.5).
Format
push(ARRAY, LIST)
Example 5.22
(In Script) use warnings; # Adding elements to the end of a list 1 my @names=("Bob", "Dan", "Tom", "Guy"); 2 push(@names, "Jim", "Joseph", "Archie"); 3 print "@names \n"; (Output) 2 Bob Dan Tom Guy Jim Joseph Archie
Explanation
- 1. The array @names is assigned list values.
- 2. The push function pushes three more elements onto the end of the array.
- 3. The new array has three more elements appended to it.
Figure 5.5 Adding elements to an array.
The unshift Function.
The unshift function prepends LIST to the front of the array (see Figure 5.6).
Format
unshift(ARRAY, LIST)
Example 5.23
(In Script) use warnings; # Putting new elements at the front of a list 1 my @names=("Jody", "Bert", "Tom") ; 2 unshift(@names, "Liz", "Daniel"); 3 print "@names\n"; (Output) 3 Liz Daniel Jody Bert Tom
Explanation
- 1. The array @names is assigned three values, “Jody”, “Bert”, and “Tom”.
2. The unshift function will prepend “Liz” and “Daniel” to the array.
Figure 5.6 Using the unshift function to add elements to the beginning of an array.
5.3.2 Removing and Replacing Elements
The delete Function.
If you have a row of shoeboxes and take a pair of shoes from one of the boxes, the number of shoeboxes remains the same, but one of them is now empty. That is how delete works with arrays. The delete function allows you to remove a value from an element of an array, but not the element itself. The value deleted is simply undefined. (See Figure 5.7.) But if you find it in older programs, perldoc.perl.org warns not to use it for arrays, but rather for deleting elements from a hash. In fact, perldoc.perl.org warns that calling delete on array values is deprecated and likely to be removed in a future version of Perl.
Figure 5.7 Using the delete function to remove elements from an array.
Instead, use the splice function to delete and replace elements from an array, while at the same time renumbering the index values.
The splice Function.
For the delete function, we described a row of shoeboxes in which a pair of shoes was removed from one of the boxes, but the box itself remained in the row. With splice, the box and its shoes can be removed and the remaining boxes pushed into place. (See Figure 5.8.) We could even take out a pair of shoes and replace them with a different pair (see Figure 5.9), or add a new box of shoes anywhere in the row. Put simply, the splice function removes and replaces elements in an array. The OFFSET is the starting position where elements are to be removed. The LENGTH is the number of items from the OFFSET position to be removed. The LIST consists of an optional new elements that are to replace the old ones. All index values are renumbered for the new array.
Format
splice(ARRAY, OFFSET, LENGTH, LIST) splice(ARRAY, OFFSET, LENGTH) splice(ARRAY, OFFSET)
Example 5.24
(The Script) use warnings; # Splicing out elements of a list 1 my @colors=("red", "green", "purple", "blue", "brown"); 2 print "The original array is @colors\n"; 3 my @discarded = splice(@colors, 2, 2); 4 print "The elements removed after the splice are: @discarded.\n"; 5 print "The spliced array is now @colors.\n"; (Output) 2 The original array is red green purple blue brown. 4 The elements removed after the splice are: purple blue. 5 The spliced array is now red green brown.
Explanation
- 1. An array of five colors is created.
3. The splice function removes elements purple and blue from the array and returns them to @discarded, starting at index position two, $colors[2], with a length of two elements.
Figure 5.8 Using the splice function to remove or replace elements in an array.
Example 5.25
(The Script) use warnings; # Splicing and replacing elements of a list 1 my @colors=("red", "green", "purple", "blue", "brown"); 2 print "The original array is @colors\n"; 3 my @lostcolors=splice(@colors, 2, 3, "yellow", "orange"); 4 print "The removed items are @lostcolors\n"; 5 print "The spliced array is now @colors\n"; (Output) 2 The original array is red green purple blue brown 4 The removed items are purple blue brown 5 The spliced array is now red green yellow orange
Explanation
- An array of five colors is created.
- The original array is printed.
- The splice function will delete elements starting at $colors[2] and remove the next three elements. The removed elements (purple, blue, and brown) are stored in @lostcolors. The colors yellow and orange will replace the ones that were removed.
- The values that were removed are stored in @lostcolors and printed.
The new array, after the splice, is printed.
Figure 5.9 Splicing and replacing elements in an array.
The pop Function.
The pop function pops off the last element of an array and returns it. The array size is subsequently decreased by one. (See Figure 5.10.)
Format
pop(ARRAY) pop ARRAY
Example 5.26
(In Script) use warnings; # Removing an element from the end of a list 1 my @names=("Bob", "Dan", "Tom", "Guy"); 2 print "@names\n"; 3 my $got = pop @names; # Pops off last element of the array 4 print "$got\n"; 5 print "@names\n"; (Output) 2 Bob Dan Tom Guy 4 Guy 5 Bob Dan Tom
Explanation
- 1. The @name array is assigned a list of elements.
- 2. The array is printed.
- 3. The pop function removes the last element of the array and returns the popped item.
- 4. The $got scalar contains the popped item, Guy.
5. The new array is printed.
Figure 5.10 Using the pop function to pop the last element off the array.
The shift Function.
The shift function shifts off and returns the first element of an array, decreasing the size of the array by one element. (See Figure 5.11.) If ARRAY is omitted, then the @ARGV array is shifted. If in a subroutine, the argument list, stored in the @_ array is shifted.
Format
shift(ARRAY) shift ARRAY shift
Example 5.27
(In Script) use warnings; # Removing elements from front of a list 1 my @names=("Bob", "Dan", "Tom", "Guy"); 2 my $ret = shift @names; 3 print "@names\n"; 4 print "The item shifted is $ret.\n"; (Output) 3 Dan Tom Guy 4 The item shifted is Bob.
Explanation
- 1. The array @names is assigned list values.
- 2. The shift function removes the first element of the array and returns that element to the scalar $ret, which is Bob.
3. The new array has been shortened by one element.
Figure 5.11 Using the shift function to return the first element of an array.
5.3.3 Deleting Newlines
The chop and chomp Functions (with Lists).
The chop function chops off the last character of a string and returns the chopped character, usually for removing the newline after input is assigned to a scalar variable. If a list is chopped, chop will remove the last letter of each string in the list.
The chomp function removes a newline character at the end of a string or for each element in a list.
Format
chop(LIST) chomp(LIST)
Example 5.28
(In the Script) use warnings; # Chopping and chomping a list 1 my @line=("red", "green", "orange"); 2 chop(@line); # Chops the last character off each # string in the list 3 print "@line"; 4 @line=( "red\n", "green\n", "orange\n"); 5 chomp(@line); # Chomps the newline off each string in the list 6 print "@line"; (Output) 3 re gree orang 6 red green orange
Explanation
- 1. The array @line is assigned a list of elements.
- 2. The array is chopped. The chop function chops the last character from each element of the array.
- 3. The chopped array is printed.
- 4. The array @line is assigned a list of elements.
- 5. The chomp function will chop off the newline character from each word in the array. This is a safer function than chop.
- 6. If there are no newlines on the end of the words in the array, chomp will not do anything.
5.3.4 Searching for Elements and Index Values
The grep Function.
The grep function is similar to the UNIX grep command in that it searches for patterns of characters, called regular expressions. However, unlike the UNIX grep, it is not limited to using regular expressions. Perl’s grep evaluates the expression (EXPR) for each element of the array (LIST), locally setting $_ to each element. The return value is another array consisting of those elements for which the expression evaluated as true. As a scalar value, the return value is the number of times the expression was true (that is, the number of times the pattern was found).
Format
grep BLOCK LIST grep(EXPR,LIST)
Example 5.29
(The Script) use warnings; # Searching for patterns in a list 1 my @list = ("tomatoes", "tomorrow", "potatoes", "phantom", "Tommy"); 2 my $count = grep($_ =~ /tom/i, @list); # $count = grep(/tom/i, @list); 3 @items= grep(/tom/i, @list); # Could say: grep {/tom/i} @list; 4 print "Found items: @items\nNumber found: $count\n"; (Output) 4 Found items: tomatoes tomorrow phantom Tommy Number found: 4
Explanation
- 1. The array @list is assigned a list of elements.
- 2. The grep function searches for the pattern (regular expression) tom. The $_ scalar is used as a placeholder for each item in the iterator @list. ($_ is also an alias to each of the list values, so it can modify the list values.) Although omitted in the next example, it is still being used. The i turns off case sensitivity. When the return value is assigned to a scalar, the result is the number of times the regular expression was matched.
- 3. grep again searches for tom. The i turns off case sensitivity. When the return value is assigned to an array, the result is a list of the matched items.
The next example shows you how to find the index value(s) for specific elements in an array using the built-in grep function. (If you have version 5.10+, you may want to use the more efficient List::MoreUtils module from the standard Perl libaray, or from CPAN.)
Example 5.30
(The Script) use warnings; my(@colors, $index); # Searching for the index value where a pattern is found. 1 @colors = qw(red green blue orange blueblack); 2 @index_vals = grep( $colors[$_] =~ /blue/, (0..$#colors)); 3 print "Found index values: @index_vals where blue was found.\n"; (Output) 3 Found index values: 2 4 where blue was found.
Explanation
- 1. The array @colors is assigned a list of elements.
- 2. The grep function searches for the pattern blue in each element of @colors. (See Chapter 8, “Regular Expressions—Pattern Matching,” for a detailed discussion on pattern matching.) The list (0 .. $#colors) represents the index values of @colors. $_ holds one value at a time from the list starting with 0. If, for example, in the first iteration, grep searches for the pattern blue in $colors[0], and finds red, nothing is returned because it doesn’t match. (=~ is the bind operator.) Then, the next item is checked. Does the value $colors[1], green, match blue? No. Then, the next item is checked. Does $colors[2] match blue? Yes it does. 2 is returned and stored in @index_vals. Another match for blue is true when $colors[4], blueblack, is matched against blue. 4 is added to @index_vals.
- 3. When the grep function finishes iterating over the list of index values, the results stored in @index_vals are printed.
5.3.5 Creating a List from a Scalar
The split Function.
The split function splits up a string (EXPR) by some delimiter (whitespace, by default) and returns a list. (See Figure 5.12.) The first argument is the delimiter, and the second is the string to be split. The Perl split function can be used to create fields when processing files, just as you would with the UNIX awk command. If a string is not supplied as the expression, the $_ string is split.
The DELIMITER statement matches the delimiters that are used to separate the fields. If DELIMITER is omitted, the delimiter defaults to whitespace (spaces, tabs, or newlines). If the DELIMITER doesn’t match a delimiter, split returns the original string. You can specify more than one delimiter, using the regular expression metacharacter [ ]. For example, [ +\t:] represents zero or more spaces or a tab or a colon.
To split on a dot (.), use /\./ to escape the dot from its regular expression metacharacter.
LIMIT specifies the number of fields that can be split. If there are more than LIMIT fields, the remaining fields will all be part of the last one. If the LIMIT is omitted, the split function has its own LIMIT, which is one more than the number of fields in EXPR. (See the -a switch for autosplit mode, in Appendix A, “Perl Built-ins, Pragmas, Modules, and the Debugger.”)
Format
split("DELIMITER",EXPR,LIMIT) split(/DELIMITER/,EXPR,LIMIT) split(/DELIMITER/,EXPR) split("DELIMITER",EXPR) split(/DELIMITER/) split
Example 5.31
(The Script) use warnings; # Splitting a scalar on whitespace and creating a list 1 my $line="a b c d e"; 2 my @letter=split(' ',$line); 3 print "The first letter is $letter[0]\n"; 4 print "The second letter is $letter[1]\n"; (Output) 3 The first letter is a 4 The second letter is b
Explanation
- 1. The scalar variable $line is assigned the string a b c d e.
- 2. The value in $line (scalar) is a single string of letters. The split function will split the string, using whitespace as a delimiter. The @letter array will be assigned the individual elements a, b, c, d, and e. Using single quotes as the delimiter is not the same as using the regular expression / /. The ‘ ’ resembles awk in splitting lines on whitespace. Leading whitespace is ignored. The regular expression / / includes leading whitespace, creating as many null initial fields as there are whitespaces.
- 3. The first element of the @letter array is printed.
4. The second element of the @letter array is printed.
Figure 5.12 Using the split function to create an array from a scalar.
Example 5.32
(The Script) use warnings; # Splitting up $_ my @line; 1 while(<DATA>){ 2 @line=split(":"); # or split (/:/, $_); 3 print "$line[0]\n"; } _ _DATA_ _ Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500 Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400 Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700 Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900 Fred Fardbarkle:674-843-1385:20 Park Lane, Duluth, MN 23850:4/12/23:78900 (Output) Betty Boop Igor Chevsky Norma Corder Jennifer Cowan Fred Fardbarkle
Explanation
- 1. The $_ variable holds each line of the file DATA filehandle; the data being processed is below the _ _DATA_ _ line. Each line is assigned to $_. $_ is also the default line for split.
- 2. The split function splits the line, ($_), using the : as a delimiter and returns the line to the array, @line.
- 3. The first element of the @line array, line[0], is printed.
Example 5.33
(The Script) use warnings; my($name, $phone, $address, $bd, $sal); # Splitting up $_ and creating an unnamed list while(<DATA>){ 1 ($name,$phone,$address,$bd,$sal)=split(":"); 2 print "$name\t $phone\n" ; } _ _DATA_ _ Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500 Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400 Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700 Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900 Fred Fardbarkle:674-843-1385:20 Park Lane, Duluth, MN 23850:4/12/23:78900 (Output) 2 Betty Boop 245-836-8357 Igor Chevsky 385-375-8395 Norma Corder 397-857-2735 Jennifer Cowan 548-834-2348 Fred Fardbarkle 674-843-1385
Explanation
- 1. Perl loops through the DATA filehandle one line at a time from _ _DATA_ _, storing each successive item in the $_ variable, overwriting what was previously stored there. The split function splits each line in $_, using the colon as a delimiter.
- 2. The returned list consists of five scalars, $name, $phone, $address, $bd, and $sal. The values of $name and $phone are printed.
Example 5.34
(The Script) use warnings; # Many ways to split a scalar to create a list 1 my $string= "Joe Blow:11/12/86:10 Main St.:Boston, MA:02530"; 2 my @line=split(":", $string); # The string delimiter is a colon 3 print @line,"\n"; 4 print "The guy's name is $line[0].\n"; 5 print "The birthday is $line[1].\n\n"; 6 @line=split(":", $string, 2); 7 print $line[0],"\n"; # The first element of the array 8 print $line[1],"\n"; # The rest of the array because limit is 2 9 print $line[2],"\n"; # Nothing is printed 10 ($name, $birth, $address)=split(":", $string); 11 print $name,"\n"; 12 print $birth,"\n"; 13 print $address,"\n"; (Output) 3 Joe Blow11/12/8610 Main St.Boston, MA02530 4 The guy's name is Joe Blow. 5 The birthday is 11/12/86. 7 Joe Blow 8 11/12/86:10 Main St.:Boston, MA:02530 9 11 Joe Blow 12 11/12/86 13 10 Main St.
Explanation
- 1. The scalar $string is split at each colon.
- 2. The delimiter is a colon. The limit is 2.
- 6. The string is split by colons and given a limit of two, meaning that the text up to the first colon will become the first element of the array; in this case, $line[0] and the rest of the string will be assigned to $line[1]. LIMIT, if not stated, will be one more than the total number of fields.
- 10. The string is split by colons and returns a list of scalars. This may make the code easier to read.
5.3.6 Creating a Scalar from a List
The join Function.
The join function joins the elements of an array into a single string and separates each element of the array with a given delimiter, sometimes called the “glue” character(s) since it glues together the items in a list (opposite of split). (See Figure 5.13.) The expression DELIMITER is the value of the string that will join the array elements in LIST.
Format
join(DELIMITER, LIST)
Example 5.35
(The Script) use warnings; my(@colors, $color_string); # Joining each elements of a list with commas 1 @colors = qw( red green blue); 2 $color_string = join(", ",@colors); # Create a string from an array 3 print "The new string is: $color_string\n"; (Output) 3 The new string is: red, green, blue
Explanation
- 1. An array is assigned three colors.
- 2. The join function joins the three elements of the @colors array, using a comma and space as the delimiter returning a string, which is then assigned to $color_string.
- 3. The new string with commas is printed.
Figure 5.13 Using the join function to join elements of an array with a comma.
Example 5.36
(The Script) use warnings; # Joining each element of a list with a newline 1 my @names= qw(Dan Dee Scotty Liz Tom); 2 @names=join("\n", sort(@names)); 3 print @names,"\n"; (Output) 3 Dan Dee Liz Scotty Tom
Explanation
- 1. The array @names is assigned a list of strings.
- 2. The join function will join each word in the list with a newline (\n) after the list has been sorted alphabetically.
- 3. The sorted list is printed with each element of the array on a line of its own.
5.3.7 Transforming an Array
The map Function.
If you have an array and want to perform the same action on each element of the array without using a for loop, the map function may be an option. The map function maps each of the values in an array to an expression or block, returning another list with the results of the mapping. It lets you change the values of the original list.
Format
map EXPR, LIST; map {BLOCK} LIST;
Using map to Change All Elements of an Array
In the following example, the chr function is applied or mapped to each element of an array and returns a new array showing the results. (See Figure 5.14.)
Example 5.37
(The Script) use warnings; my(@list, @words, @n); # Mapping a list to an expression 1 my @list=(0x53,0x77,0x65,0x64,0x65,0x6e,012); 2 my @letters = map chr $_, @list; 3 print @letters; 4 my @n = (2, 4, 6, 8); 5 @n = map $_ * 2 + 6, @n; 6 print "@n\n"; (Output) 3 Sweden 6 10 14 18 22
Explanation
- 1. The array @list consists of six hexadecimal numbers and one octal number.
- 2. The map function maps each item in @list to its corresponding chr (character) value and returns a new list, assigned to @letters. (According to perldoc.perl.org, the chr function “returns the character represented by that NUMBER in the character set. For example, chr(65) is “A” in either ASCII or Unicode, and chr(0x263a) is a Unicode smiley face.”)
- 3. The new list is printed. Each numeric value was converted with the chr function to a character corresponding to its ASCII value; for example, chr(65) returns ASCII value “A”.
- 4. The array @n consists of a list of integers.
- 5. The map function evaluates the expression for each element in the @n array and returns the result to the new array @n.
6. The results of the mapping are printed, showing that the original list has been changed.
Figure 5.14 Using the map function to change elements in an array.
Using map to Remove Duplicates from an Array
The map function can be used to create a hash from an array. If you are using the array elements as keys for the new hash, any duplicates will be eliminated.
Example 5.38
(The Script) use warnings; my(@courses, %c); 1 @courses=qw( C++ C Perl Python French C C Perl); 2 %c = map { $_ => undef } @courses; # Create a unique list of keys 3 @courses = keys %c; 4 print "@courses\n"; (Output) Python, French, Perl, C, C++
Explanation
- 1. The array of courses contains duplicates.
- 2. The map function is used to create a hash called %c. Each element in the array @courses is assigned in turn to $_. $_ serves as the key to the new %c hash. The value is left undefined since the keys are all we need to get a list of unique courses.
- 3. The keys in the %c hash are assigned to @courses, overwriting what was there. The new list will have no duplicate entries, although it will be unordered, as are all hashes.
5.3.8 Sorting an Array
The sort Function.
The sort function sorts and returns a sorted list. Its default is to sort alphabetically, but you can define how you want to sort by using different comparison operators. If SUBROUTINE is specified, the first argument to sort is the name of the subroutine, followed by a list of values to be sorted. If the string cmp operator is used, the values in the list will be sorted alphabetically (ASCII sort), and if the <=> operator (called the space ship operator) is used, the values will be sorted numerically. The values are passed to the subroutine by reference and are received by the special Perl variables $a and $b, not the normal @_ array. (See Chapter 11, “How Do Subroutines Function?” for further discussion.) Do not try to modify $a or $b, as they represent the values that are being sorted.
If you want Perl to sort your data according to a particular locale, your program should include the use locale pragma. For a complete discussion, see perldoc.perl.org/perllocale.
Format
sort(SUBROUTINE LIST) sort(LIST) sort SUBROUTINE LIST sort LIST
Example 5.39
(The Script) use warnings; # Simple alphabetic sort 1 my @list=("dog","cat","bird","snake" ); print "Original list: @list\n"; 2 my @sorted = sort @list; 3 print "ASCII sort: @sorted\n"; # Reversed alphabetic sort 4 @sorted = reverse sort @list; print "Reversed ASCII sort: @sorted\n"; (Output) Original list: dog cat bird snake ASCII sort: bird cat dog snake Reversed ASCII sort: snake dog cat bird
Explanation
- 1. The @list array will contain a list of items to be sorted.
- 2.The sort function performs a string (lexographical for current locale) sort on the items. The sorted values must be assigned to another list or the same list. The sort function doesn’t change the original list.
- 3. The sorted string is printed.
- 4. This list is sorted alphabetically and then reversed.
ASCII and Numeric Sort Using Subroutine
You can either define a subroutine or use an inline function to perform customized sorting, as shown in the following examples. A note about $a and $b: they are special global Perl variables used by the sort function for comparing values. If you need more information on the operators used, see Chapter 6, “Where’s the Operator?”
Example 5.40
(The Script) use warnings; 1 my @list=("dog","cat", "bird","snake" ); print "Original list: @list\n"; # ASCII sort using a subroutine 2 sub asc_sort{ 3 $a cmp $b; # Sort ascending order } 4 @sorted_list=sort asc_sort(@list); print "ASCII sort: @sorted_list\n"; # Numeric sort using subroutine 5 sub numeric_sort { $a <=> $b ; } # $a and $b are compared numerically 6 @number_sort=sort numeric_sort 10, 0, 5, 9.5, 10, 1000; print "Numeric sort: @number_sort.\n"; (Output) Original list: dog cat bird snake ASCII sort: bird cat dog snake Numeric sort: 0 5 9.5 10 10 1000.
Explanation
- 1. The @list array will contain a list of items to be sorted.
- 2. The subroutine asc_sort() is sent a list of strings to be sorted.
- 3. The special global variables $a and $b are used when comparing the items to be sorted in ascending order. If $a and $b are reversed (for example, $b cmp $a), then the sort is done in descending order. The cmp operator is used when comparing strings.
- 4. The sort function sends a list to the asc_sort(), user-defined subroutine, where the sorting is done. The sorted list will be returned and stored in @sorted_list.
- 5. This is a user-defined subroutine, called numeric_sort(). The special variables $a and $b compare the items to be sorted numerically, in ascending order. If $a and $b are reversed (for example, $b <=> $a), then the sort is done in numeric descending order. The <=> operator is used when comparing numbers.
- 6. The sort function sends a list of numbers to the numeric_sort() function and gets back a list of sorted numbers, stored in the @number_sort array.
Example 5.41
(The Script) use warnings; # Sorting numbers with block 1 my @sorted_numbers = sort {$a <=> $b} (3,4,1,2); 2 print "The sorted numbers are: @sorted_numbers", ".\n"; (Output) 2 The sorted numbers are: 1 2 3 4.
Explanation
- The sort function is given a block, also called an inline subroutine, to sort a list of numbers passed as arguments. The <=> operator is used with variables $a and $b to compare the numbers. The sorted numeric list is returned and stored in the array @sorted_numbers. (See http://perldoc.perl.org/functions/sort.html for more on the sort function.)
- The sorted list is printed.
5.3.9 Checking the Existence of an Array Index Value
The exists Function.
The exists function returns true if an array index (or hash key) has been defined, and false if it has not. It is most commonly used when testing a hash key’s existence.
Format
exists $ARRAY[index];
Example 5.42
use warnings; 1 my @names = qw(Tom Raul Steve Jon); 2 print "Hello $names[1]\n", if exists $names[1]; 3 print "Out of range!\n", if not exists $names[5]; (Output) 2 Hello Raul 3 Out of range!
Explanation
- 1. An array of names is assigned to @names.
- 2. If the index 1 is defined, the exists function returns true and the string is printed.
- 3. If the index 5 does not exist (and in this example it doesn’t), then the string Out of range! is printed.
5.3.10 Reversing an Array
The reverse Function.
The reverse function reverses the elements in a list, so that if the values appeared in descending order, now they are in ascending order, or vice versa. In scalar context, it concatenates the list elements and returns a string with all the characters reversed; for example, in scalar context Hello, there! reverses to !ereht ,olleH.
Format
reverse(LIST) reverse LIST
Example 5.43
(In Script) use warnings; my(@names, @reversed); # Reversing the elements of an array 1 @names=("Bob", "Dan", "Tom", "Guy"); 2 print "@names \n"; 3 my @reversed=reverse @names,"\n"; 4 print "@reversed\n"; (Output) 2 Bob Dan Tom Guy 4 Guy Tom Dan Bob
Explanation
- 1. The array @names is assigned list values.
- 2. The original array is printed.
- 3. The reverse function reverses the elements in the list and returns the reversed list. It does not change the original array; that is, the array @names is not changed. The reversed items are stored in @reversed.
- 4.The reversed array is printed.