Lesson 12 | Perl Split function |
Objective | Lesson 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.
Perl File input output.
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