Lists and arrays

an article added by: Sarah Miller at 04242008


In: Categories » Internet and online » Web services » Lists and arrays

A few more features of Perl must be covered before any more interesting programs can be written. First, we need Perl’s ‘lists’ (or ‘arrays’). A Perl list is like a dynamic array class in C++ or Java (e.g. java.util.Vector). Lists do not use Perl’s object syntax, but a list is basically an object that owns data and which has an associated group of functions. A Perl list:

Owns a collection of data elements (usually scalar values, but you can build lists of lists and other more complex structures as explained in the perldsc. Does (OK, ‘has done to it’, as these are not class member functions):

– Create a list, usually initializing it with a non-empty set of data elements (though empty lists are fine).

– Add elements ‘at front’ or ‘at end’ of the list.

– Remove elements ‘at front’ or ‘at end’ of the lists.

– Access elements at specific positions (this feature gives it ‘array’-like behaviors as well as list behaviors).

– Return the size of its collection (length of dynamic array).

– Copy into another array.

Other functions related to lists include functions for sorting lists and for returning copies of lists with the elements in reversed order.

Lists are designated using the ‘@’ type qualifier. Their names follow the usual conventions

– letter followed by alphanumerics (and some other characters in the special names for lists supplied in the Perl core). When forming names, Perl considers the underscore character as a letter. Valid list names are:

@mylist
   @results
   @inputlines
   @_data
   @list_1

Perl maintains distinct ‘namespaces’ for its different scalar, list and hash data types (and other types like ‘file handles’). You can have a scalar $results and a list @results without causing Perl any confusion (though you may upset an inexperienced maintenance programmer who has to look after your code).

List literals are supported:
   (1, 2, 3)
   ( "tom", "dick", "harry", "sue")
 ( $name, $address, $town)

List literals are often used to initialize arrays. Another usage has the list literal as an ‘lvalue’ (something on the left-hand side of an assignment statement). This usage will be illustrated later; it is a convenience feature related to the extraction of specific elements from an existing list. Some examples of list literals being used in list/array creation are:

@PlacesIveBeen = (); # I've been nowhere yet - so, an empty list
   @GradePts = (45, 50, 65, 75, 85);
   @Cities = ( "London", "Paris", "New York", "Rome", "Tokyo", "Sydney");
   @people = ( "tom", "dick", "harry", "sue");
   @TeenYears = (13 .. 19);

The last of these illustrates Perl’s ‘..’ range operator. This is a short way of defining the collection as (13, 14, 15, 16, 17, 18, 19). Range operators can be used in ‘foreach’ iterative constructs – for (1..100); foreach loops are explained later in this article. Since it is common to need to initialize a list of words, Perl has a helper function qw(). Thus, you could have:

@people = qw( tom dick harry sue );

The qw() function isn't always appropriate. The following usage:

@Cities = qw (London Paris 'New York' Rome Tokyo Sydney);

results in a list like: (London, Paris, 'New, York', Rome, Tokyo, Sydney) which is probably not what was intended. The following code fragment illustrates the creation and use of some lists. The loops illustrate different ways of accessing the list elements:

@Cities1 = ("London", "Paris", "New York"); # a list with 3 elements
   @Cities2 = qw( Rome 'Los Angeles' "San Francisco"); # 5 elements!
   @Cities3 = ("Wagga", "Hay", "Cooma");
   #like qq() and q(), qw() allows other delimiters:
   @Cities4 = qw\ Thiroul Bellambi Keiraville\;
   print "Cities1 :\n";
   $size = @Cities1;
   for($i=0;$i<$size;$i++) {
   print $Cities1[$i] , "\n";
   }
   print "Cities1 :\n";
   foreach $city (@Cities2) {
   print $city , "\n";
   }
   print "Cities3 :\n";
   foreach $i (0 .. $#Cities3) {
   print $Cities3[$i] , "\n";
   }
   print "Cities4 :@Cities4\n";
   print @Cities4;

The line $size = @Cities1; illustrates the use of an array in a ‘scalar context’; Perl interprets this as a request for the length of the array; so $size takes the value 3. The first for loop is a conventional counting loop, with the loop index used to index into the @Cities1 collection. Note the usage $Cities[$i]; the data type here is a scalar – we are extracting a single data element from the specified position in the collection. The second and third for loops are examples of Perl’s foreach loop construct. These loops have the form:

foreach <variable> (list) block
   foreach (list) block

(The keyword formay be used instead of foreach, but foreach is more readable.) Usually you want a variable that references the current element from the list, but this is not essential. The first of the foreach loops in the example code simply accesses each of the (five!) elements in $Cities2, printing the name of each in turn. The second is more like a counting for loop; the expression $#Cities3 returns the (scalar) value that is the index of the last element of the list @Cities3. Consequently, this loop is really foreach $i (0, 1, 2) { ... }; this loop again uses array style indexing to extract data elements from the list. Finally, the list $Cities4 is printed twice. The first print statement has the list interpolated into a string; this prints the elements separated by spaces. The final print statement results in a line with all data elements concatenated into one long string (not a particularly useful form of output, just another feature of the Perl system). Lists can be concatenated together:

@Male = qw(Mickey Donald);
   @Female = qw(Minnie Daisy);
   @DisneyMob = (@Male, @Female, "Pluto");

This produces a single-level list (not a Lisp-like list of lists):

Mickey, Donald, Minnie, Daisy, Pluto
   Arrays can be ‘sliced’ to give subarrays:
   @line = qw(one two three four);
   @firsttwo = @line[0,1];
   @line[0,1] = ("five", "six");

or can have values pushed and popped:

@stack = ();
   push(@stack, "one");
   push(@stack, "two");
   push(@stack, 3, 4);
   push(@stack, 5, 6, 7, 8, "nine", 101 );
   print @stack, "\n";
   $val = pop(@stack);
   print "@stack\n";

(shift and unshift work in a similar way, operating at the start rather than the end of a list. You can combine pushing and shifting etc. to achieve something like a double-ended queue.) The reverse function returns a copy of the list with the elements in reverse order. By default, the sort function uses an alphabetic sort, treating all list elements as strings; again it returns a new list.

@newRevList = reverse(@aList);
   @list1 = qw(This is a test what else Hello World Hi mom etc etc);
   # Prints as :
   List1: This is a test what else Hello World Hi mom etc etc
   # Peform sort, then print sorted list; upper case letters rank
   # lower than lower case letters ...
   Sorted: Hello Hi This World a else etc etc is mom test what
   #Some numeric data
   @list2 = ( 100, 26, 3, 49, -11, 3001, 78);
# Sorted! (Sorted alphabetically)
 Sorted:-11 100 26 3 3001 49 78

The default sort behavior of alphabetic sorting can be modified; you have to provide your own sort helper subroutine. The helper functions for sorting are a little atypical of user-defined routines, but they are not hard to write. Your routine will be called to return the result of a comparison operation on two elements from the array – these elements will have been placed in the global variables $a and $b prior to the call to your subroutine. (This use of specific global variables is what makes these sort subroutines different from other programmer-defined routines.) The following code illustrates the definition and use of a sort helper subroutine ‘numeric_sort’.

#!/share/bin/perl -w
   sub numeric_sort {
   if($a < $b) { return -1; }
   elsif($a == $b) { return 0; }
   else { return 1; }
   }
   @list2 = ( 100, 26, 3, 49, -11, 3001, 78);
   @slist2 = sort @list2;
   print "List2 @list2\n";
   print "Sorted List2 (default sort) @slist2\n";
   @nlist2 = sort numeric_sort @list2;
   print "Sorted List2 (numeric sort) @nlist2\n";

Perl has a special <=> operator for numeric comparisons; using this operator, the numeric sort function could be simplified:

sub numeric_sort {
   @a <=> $b
   }

Perl permits in-line definition of sort helper functions, allowing constructs such as:

@nlist2 = sort { $a <=> $b } @list2;

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. The vBulletin Administrator Experience
The vBulletin Administrator Experience What are the differences for an administrator compared to a regular member? Well, there are quite a few. We'll take a look at some of the more important ones now. Forum and Thread Tools The first differences are the forum and thread tools. Forum tools allow the administrator to view the posts and attachments that are in the moderator queue. (These are the posts and attachments that need to be approved before being made visible.) Th...

2. Generation of dynamic pages
Most of this text is concerned with elaborate ways of creating dynamic pages through Perl scripts, PHP scripts, Java servlets and Java Server Pages. The basic Apache setup provides support for CGI programs (based on Perl scripts and alternatives), and for the fairly limited ‘server-side includes’ (SSI) mechanism. The relevant modules (mod_env, mod_cgi and mod_include) are included in the default Apache build. It is best to limit the number of directories that contain executable code that can generate dynamic pages. The...

3. The next few elements define options
In this example, the defaults for htdocs and its subdirectories are set to allow clients to view the contents of a directory (as a page with a list of files, or something prettier), enable support for content negotiation, and permit the use of Unix inter-directory links. The next subdirective, AllowOverride, makes provision for overriding .htaccess files in subdirectories. The options here allow you to specify that nothing be changed (as in the example with AllowOverride None), or that anything be changed (AllowOverride Any...

4. Slightly modified specification for a CS1 program
The manager of a fast food outlet requires a program to help track sales. The outlet only serves burgers with fries; a burger meal costs $5.95. Customers may order any number of burger meals. The program is to help calculate prices of orders, and is also to keep records of total orders and the largest single order. The program is to use a simple menu-select style loop with the options: (1) Place order (2) Print totals so far (3) Quit The order option should result in a prompt for the number of meals ...

5. Each output line consists of a list of words
These lines have to be sorted using an alphabetic ordering that uses the sub-string starting at the keyword. The keyword starts after column 50, so we require a special sort helper routine that picks out these sub-strings. The sort routine is similar to the numeric_sort illustrated earlier. It relies on the convention that, before the routine is called, the global variables $a and $b will have been assigned the two data elements (in this case report lines) that must be compared. sub by_keystr { my $str1 = substr($a...

6. Finding what matched and other advanced features
Sometimes, all that you need is to know is whether input text matched a pattern. More commonly, you want to further process the specific data that were matched. For example, you hope that data from your web form contain a valid credit card number – a sequence of 13 to 16 digits. You would not simply want to verify the occurrence of this pattern; what you would want to do is to extract the digit sequence that was matched, so that you could apply further verification checks. Regular expressions allow you to define group...

7. Database example
This example illustrates basic use of Perl’s DBI module. The database contains records of people who wish to participate in an email-based ‘pen-pal’ service. Subscribers provide their email address, some limited personal information and a set of interests chosen from a predefined set of about 100 possible topics. Searches can be made for other subscribers who share some common interests, and satisfy other constraints. The database has just one table; the rows characterize subscribers to this ‘E-Pal&rsqu...