|
|
The split function in Perl is a highly versatile function and is very useful when you want to parse a line containing multiple tokens or a variable number of tokens.
Listing C.17 split1.pl
my($discard1) = ""; my($discard2) = ""; my($index) = 0; my(@numbersArray); my($currentLine) = "mumbo jumbo 1 2 3"; ($discard1, $discard2, @numbersArray) = split(/\s+/, $currentLine); foreach $index (0..$#numbersArray) { print "Number $index equals $numbersArray[$index]\n"; }
You can launch the Perl script split1.pl in Listing C.17 from the command line as follows,
perl -w split1.pl
and the output is as follows:
Number 0 equals 1 Number 1 equals 2 Number 2 equals 3
If you do not know how many tokens there are in a line, or the number of tokens varies between different lines, you can do something like this:
(@lineArray) = split(/\s+/, $currentLine); my($count) = scalar(@lineArray); print "$currentLine has $count tokens\n";
If a line uses a colon (:) as a delimiter between tokens, you can use the following variant:
(@lineArray) = split(/:/, $currentLine);
|
|