Splitting Record into Fields

Domain Hosting image
Web Hosting
Dedicated server
ssl certificate
Web Design image
Email

This example will show you how to read a file line-by-line and break the input records into fields based on a separator string. The file, FIELDS.DAT, will be used with the following contents:

121 2-.Jan:Jaspree: Painter

3453: Kelly: Horton:Jockey

The individual fields or values are separated from each other by the colon (:) character. The split() function will be used to create an array of fields. Then a foreach loop will print the fields. The coding below shows how to input lines from a file and split them into fields.

@fieldList = qw(fName IName job age);
open(FILE, " while() {
@data{@fieldList) = split(/:/, $-, scalar @fieldList);
foreach (@fieldList){
( printf("%10.10s = %s\n", $-, $data($-));
}
}
close(FILE);
This program will display:
fName = 1212
lName = Jan
job = Jaspree
age = Painter
fName=3453
!Name=kelly
job=Hortson
age=Jockey

The first line of this program uses the qw() notation to create an array of words. It is identical to @fieldList = ("fName", "IName", "job", "age"),- but without the distracting quotes and commas. The split statement might require a little explanation. It is duplicated here so that you can focus on it.

@data{@f ield List) = split(/:/, $-, scalar @fieldList); Let's use the first line of the input file as an example. The first line looks Ilk this:

121 2:Jan:Jaspree: Painter

The first thing that happens is that split creates an array using the colon as the separator, creating an array that looks like this:

("1212", "Jan", "Jaspree", "Painter") You can substitute this list in place of the split() function in the statement

@data{@fieldList} = ("1212", "Jan", "Jaspree", "Painter"); And, you already know that @fieldList is a list of field name. So, the statement can be further simplified to:

@data(" f Name", "IName", "job", "age")=
("1212", "Jan", "Jaspree", "Painter");

This assignment statement shows that each array element on the right is with a key value on the left so that four separate hash assignments are place in this statement.



Domain Name Search

www.


Copyright (C) 2007. Web Domain design hosting. All rights reserved.