Simple list examples

an article added by: Jorge Martinez at 04262008


Web services :: Simple list examples ::

 French | Spanish | Portuguese | Italian | German | Japanese | Chinese | Korean | Russian | Arabic Bookmark and Share

Many simple databases and spreadsheets have options that let you get a listing of their contents as a text file. Such a file will contain one line for each record; fields in the record will be separated in the file by some delimiter character (usually the tab or colon character). For example, a database that recorded the names, roles, departments, rooms and phone numbers of employees might be dumped to file in a format like the following:

J.Smith:Painter:Buildings & Grounds::3456
   T.Smythe:Audit clerk:Administration:15.205:3383
 A.Solly:Help line:Sales:8.177:4222

Perl programs can be very effective for processing such data. The input lines can be broken into lists of elements. The simplest way is to use Perl’s split() function as illustrated in this example, but there are alternative ways involving more complex uses of regular expression matchers. Once the data are in lists, Perl can easily manipulate the records and so produce reports such as reverse telephone directories (mapping phone numbers to people), listing of employees with no specified room number, and so forth. The following little program (which employs a few Perl ‘tricks’) generates a report that identifies those employees who have no assigned room:

while(<STDIN>) {
   @line= split /:/ ;
   $room = $line[3];
   if(!$room) {
   print $line[0], "\n" ;
   }
   }

The main ‘trick’ here is the use of Perl's ‘anonymous’ variable. The statement while(<STDIN>) clearly reads in the next line of input and tests for an empty line, but it is not explicit as to where that input line is stored. In many places like this, Perl allows the programmer to omit reference to an explicit variable; if the context requires a variable, Perl automatically substitutes the ‘anonymous variable’ $_. (This feature is a part of the high whipitupitude level of the Perl language: you don’t have to define variables whose role is simply to hold data temporarily.) The while statement is really equivalent to while($_ = <STDIN>) { ... }. The split function is then used to break the input line into separate elements. This function is documented, as one of the regular expression and pattern matching functions. It has the following usages:

split /PATTERN/,EXPR,LIMIT
   split /PATTERN/,EXPR
   split /PATTERN/

It splits the string given by EXPR. The PATTERN element is a regular expression specifying the characters that form the element separators; here it is particularly simple: the pattern specifies the colon character used in the example data. The LIMIT element is optional: it allows you to split out the first n elements from the expression, ignoring any others. The example code uses the simplest form of split, with merely the specification of the separator pattern. Here split is implicitly operating on the anonymous variable $_ that has just had assigned the value of a string representing the next line of input. The list resulting from the splitting operation is assigned to the list variable @line. The room was the fourth element of the print lines in the dump file from the database. Array indexing style operations allow this scalar value to be extracted from the list/array @line. If this is ‘null’ (‘undef’ or undefined in Perl), the employee’s name is printed. In this example, only one element of the list was required; array-style subscripting is the appropriate way to extract the data. If more of the data were to be processed, then rather than code like the following:

$name = $line[0];
   $role = $line[1];
   $department = $line[2];
   one can use a list literal as an lvalue:
   ($name, $role, $department) = @line;

This statement copies the first three elements from the list @line into the named scalar variables. It is also possible to select a few elements into scalars, and keep the remaining elements in another array:

($name, $role, $department, @rest) = @line;
   Use of list literals would allow the first example program to be simplified to:
   while(<STDIN>) {
   ($name, $role, $department, $room, $phone) = split /:/ ;
   if(!$room) {
   print $name, "\n" ;
   }
   }

The second example is a program to produce a ‘keyword in context’ index for a set of film titles. The input data for this program are the film titles; one title per line, with keywords capitalized. Example data could be:

The Matrix
   The Empire Strikes Back
   The Return of the Jedi
   Moulin Rouge
   Picnic at Hanging Rock
   Gone with the Wind
   The Vertical Ray of the Sun
   Sabrina
   The Sound of Music
Captain Corelli's Mandolin
   The African Queen
 Casablanca

From these data, the program is to produce a permuted keyword in context index of the titles:

The African Queen
   The Empire Strikes Back
   Captain Corelli's Mandolin
   Casablanca
   Captain Corelli's Mandolin
   The Empire Strikes Back
   Gone with the Wind
   Picnic at Hanging Rock
   The Return of the Jedi
   Captain Corelli's Mandolin
   The Matrix
   Moulin Rouge
   The Sound of Music
   Picnic at Hanging Rock
   The African Queen
   The Vertical Ray of the Sun
   The Return of the Jedi
   Picnic at Hanging Rock
   Moulin Rouge
   Sabrina
   The Sound of Music
   The Empire Strikes Back
   The Vertical Ray of the Sun
   The African Queen
   The Empire Strikes Back
   The Matrix
   The Return of the Jedi
   The Sound of Music
   The Vertical Ray of the Sun
   The Vertical Ray of the Sun
   Gone with the Wind

The program has to loop, reading and processing each line of input (film title). Given a line, the program must find the keywords – these are the words that start with a capital letter. For each keyword, the program must generate a string with the context – separating the words before the keyword from the keyword and remainder of the words in the line. This generated string must be added to a collection. When all data have been read, the collection has to be sorted using a specialized sort helper routine. Finally, the sorted list is printed. (The actual coding could be made more efficient; the mechanisms used have been selected to illustrate a few more of Perl’s standard features.) The code (given in full later) has the general structure:

@collection = ();
   #read loop
   while($title = <STDIN>) {
   chomp($title);
   @Title = split / / , $title;
   ...
   foreach $i (0 .. $#Title) {
   $Word = $Title[$i];
   # if keyword, then generate another output line
   # and add to collection
   ...
   }
   }
   # sort collection using special helper function
   @sortcollection = sort by_keystr @collection;
   # print the sorted data
   foreach $entry (@sortcollection) {
   print $entry;
   }

legal disclaimer

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.

related articles

1. Blogging healthy athmosphere
As you begin to blog and appreciate the complexities, benefits, and potential offshoots of blogging, you will undoubtedly begin to wonder how to get your employees to blog. The first step is to realize that it’s entirely likely that some of your employees are already blogging. With millions of blogs in the world, assuming that none of your employees is blogging is about as naive as assuming that none of your employees has ever downloaded music online it could be true, but the odds d...

2. Employee who blogs
Internal employee blogs can be a fantastic catalyst within your company. Internal employee blogs help forge connections inside the company. External employee blogs are also great because they allow employees to connect with like-minded individuals outside the company. It doesn’t matter whether you have a dozen employees or 2000, having your staff members connect creates fantastic new opportunities especially if you’re using idea blogs, as these pairings ...

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

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

5. Apache logs
Apache expects to maintain logs recording its work. In its standard configuration, Apache records all access attempts by clients and all server-side errors (subject to a minimum severity cutoff that is set by a control parameter). There is further provision for creation of custom logs. For example, you can arrange to log data identifying the browsers used (so, if you really want to know, you can find the proportions of your clients who use Opera, Netscape, IE or another browser). You should plan how to use the data from these ...

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

7. The configuration file
If you are running your own Linux system, you can install Apache as a standard httpd daemon server that will use port 80. (You have to do the installation when logged in as the system’s administrator – root account.) You will need to create user and group accounts for your web server (as described in your Linux manuals); the usernames ‘www’ or ‘nobody’ are conventional. The user entry that you create in your /etc/password file should be appropriate for a server – no password (so it is ...

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