Fields
In previous chapters we have frequently considered text files as
being divided into records (usually lines) and
fields (usually columns separated by whitespace or
colons).
In Perl, we can take a string and decompose it into fields using
the Perl operator split . This takes two arguments, a
pattern enclosed in forward slashes, and the string, and
returns an array whose values are the fields of the string using
the pattern to describe what separates the fields. For example,
suppose string $play is set to the string "Much
Ado About Nothing" , then the following will create an array
@words containing four elements (indexed from 0 to 3)
containing strings "Much" , "Ado" ,
"About" and "Nothing" respectively:
@words = split / /, $play;
If the second argument is omitted, $_ is assumed;
if the first argument is also omitted, the split is
performed on whitespace.
Worked example
The file /etc/passwd contains colon-separated
fields specifying the users of the machine. The first field is
always the username. Write a Perl script to read the password file
and display, one per line, all the usernames.
Solution: use split to extract the
fields into an array, using pattern : to describe the
field separator, and print out the first element of the array
(index 0).
open(PASSWORDS, "/etc/passwd");
while (<PASSWORDS>) {
@cols = split /:/;
print "@cols[0]\n";
}
close(PASSWORDS);
|