Split - Page 15
March 23, 2001
We briefly saw split earlier on in the chapter,
where we used it to break up a string into a list of words. In
fact, we only saw it in a very simple form. Strictly speaking, it
was a bit of a cheat to use it at all. We didn't see it then, but
split was actually using a regular expression to do
its stuff!
Using split on its own is equivalent to saying:
split /\s+/, $_;
which breaks the default string $_ into a list of
substrings, using whitespace as a delimiter. However, we can
also specify our own regular expression: perl goes through the
string, breaking it whenever the regexp matches. The delimiter
itself is thrown away.
For instance, on the UNIX operating system, configuration files
are sometimes a list of fields separated by colons. A sample line
from the password file looks like this:
kake:x:10018:10020::/home/kake:/bin/bash
To get at each field, we can split when we see a colon:
#!/usr/bin/perl
# split.plx
use warnings;
use strict;
my $passwd =
"kake:x:10018:10020::/home/kake:/bin/bash";
my @fields = split /:/, $passwd;
print "Login name : $fields[0]\n";
print "User ID : $fields[2]\n";
print "Home directory : $fields[5]\n";
>perl split.plx
Login name : kake
User ID : 10018
Home directory : /home/kake
>
[Lines 5 and 6 above are one line. They have been split for
formatting purposes.]
Note that the fifth field has been left empty. Perl will
recognize this as an empty field, and the numbering used for the
following entries takes account of this. So
$fields[5] returns /home/kake, as we'd
otherwise expect. Be careful though - if the line you are
splitting contains empty fields at the end, they will get
dropped.
Join
To do the exact opposite, we can use the join
operator. This takes a specified delimiter and interposes it
between the elements of a specified array. For example:
#!/usr/bin/perl
# join.plx
use warnings;use strict;
my $passwd = "kake:x:10018:10020::/home/
kake:/bin/bash";my @fields
= split /:/, $passwd;print "Login name :
$fields[0]\n";print "User
ID : $fields[2]\n";print "Home directory : $fields[5]\n";
my $passwd2 = join "#", @fields;
print "Original password : $passwd\n";
print "New password : $passwd2\n";
>perl join.plx
Login name : kake
User ID : 10018
Home directory : /home/kake
Original password : kake:x:10018:10020::/home/kake:/bin/bash
New password : kake#x#10018#10020##/home/kake#/bin/bash
>
Changing Delimiters - Page 14
Beginning Perl
Transliteration - Page 16
|