Switching Word Order in Text Strings

   



The Perl split Function and Text Strings

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

start example
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"; }
end example

Remarks

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);



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net