Perl Variables  «Prev  Next»
Lesson 12Perl Split function
ObjectiveLesson describes application of the Perl Split Function

Perl Split Function

Write two programs using join and split, one of which writes an array to a file and the other which reads the array from the file. The split function splits up a delimited string into a list (or an array). This is the syntax of the split function:
split /regexp/, SCALAR, limit 

For example, the colon-delimited string from the previous lesson:
@array = ("Foo", "Bar", "Baz", "Boz");
print join(':', @array), "\n";

can be split like this:
$string = 'Foo:Bar:Baz:Boz';
@array = split(/:/, $string);

Finally, if included, the limit parameter can be used to limit the number of elements that will be created in the resulting list. For instance, this:
@array = split(/:/, $string, 3);

will result in three elements:
"Foo", "Bar", and "Baz:Bob".
In order to experiment with join and split, you will probably want to know how to read and write to files. Again, this is covered in greater detail later in the course, but we will cover the fundamentals of simple file I/O on the following page.


Simple file I/O in Perl

To open a file, you use the open() function like this:
open(HANDLE, ">filename");
  # open for write
open(HANDLE, ">>filename");
  # open for append
open(HANDLE, "<filename");
  # open for read

To write to the file, use print with the file handle:
print HANDLE
 "what to print goes here\n";

Do not use a comma after the file handle when printing to a file.
To read from a file, use one of these methods:
@array = <HANDLE>;
chomp @array; 
  # eats all the line endings

The first method reads the entire file into an array.
while(<HANDLE>) {
# chomp removes the line ending
 chomp;
# the $_ variable is
# the current line        
  print "$_\n"; 
}

The second method reads each line into the special $_ variable, and allows you to process each line separately.
To close the file, use the close function:
close(HANDLE);

For example, this program prints our Best Picture database to a file:
#!/usr/bin/perl -w
$filename = shift || "bestpix.txt";
@bestpix = ( 
"Ordinary People",
"Chariots of Fire", "Gandhi",
"Terms of Endearment", "Amadeus",
"Out of Africa", "Platoon",
"The Last Emperor", "Rain Man",
"Driving Miss Daisy",
"Dances with Wolves",
"The Silence of the Lambs",
"Unforgiven",
"Schindler's List", "Forrest Gump",
"Braveheart", "The English Patient",
"Titanic" );

open(OUTPUT, ">$filename")
 or die "can't open $filename: $!\n";
print "Writing to $filename\n";
print OUTPUT join("\n", @bestpix), "\n";
close(OUTPUT);
print "Done.\n";

This program reads it back in:
#!/usr/bin/perl -w
$filename = shift || "bestpix.txt";

open(INPUT, "< $filename")
 or  die "can't open $filename:  $! \n";
print "Reading from $filename ...\n";
@bestpix = <INPUT>;
# lose all the line endings
 chomp  @bestpix;
close(INPUT);
print join(', ', @bestpix), "\n";

A few quick notes about these programs:
  1. The line $filename = shift || "bestpix.txt" will assign a command-line parameter to $filename, or will use the default value if no command-line parameter is supplied.
  2. The die function is used to exit with an error message.
  3. The special variable $! contains the error message from the last operating-system error. It is useful for error messages like this.
  4. chomp will remove both CR and LF on DOS-based machines, or just the LF on Unix machines.
    Use this instead of the old chop wherever possible.


Perl Complete Reference

Exercise Completion

You will need the information presented below to complete the exercise link after the data. Paste the data below into a flat file and use the flat file as input to the program that you write.
Use the following data as input File for the Perl Split Function Exercise.
IBM-WebExplorer-DLL/v1.1e via Squid Cache version 1.0.5
IBM-WebExplorer-DLL/v1.1e via Squid Cache version 1.0.5
Lynx 2.5  libwww-FM/2.14
Lynx/2.6  libwww-FM/2.14
Mozilla/1.2N (Windows; I; 16bit)
Mozilla/2.0 (Win95; I)
Mozilla/2.0 (WinNT; I)
Mozilla/3.0 (Macintosh; I; PPC)
Mozilla/3.0 (Macintosh; U; PPC)
Mozilla/3.0 (X11; I; HP-UX B.10.10 9000/755)
Mozilla/3.01 (X11; I; Linux 2.0.27 i586)
Mozilla/3.01Gold (X11; I; FreeBSD 2.1.7-RELEASE i386)
Mozilla/4.0 (compatible; MSIE 4.0b1; Windows NT)
Mozilla/4.0b3 [en] (WinNT; I)  
Mozilla/4.0b3C (X11; I; SunOS 5.5 sun4u)

Perl Split Function - Exercise

Now that you have all the necessary data about join and split, try your hand at writing a pair of programs using them.
Perl Split Function - Exercise

SEMrush Software