tags:

views:

3451

answers:

4

How do you split a string e.g. "a:b:c:d" into tokens for parsing in Perl?

(e.g. using split?)

Looking for clear, straightforward answer above all (but do add any interesting tidbits of info afterwards).

+7  A: 

You can use split. You can also use it with a regex.


my @tokens = split(/:/,$string);

For more advanced parsing, I recommend Parse::RecDescent

Geo
Note that split() also takes a string as the first parameter, which is more effecient in the cases like this where it's just a simple string. split(':', $string)
mpeters
@mpeters: No, it is still a regex. try split ".", "ab.cd"; "." matches any character. And using the string " " consisting of a single space is a special case, which does not mean "match a single space"
runrig
@mpeters: What split lets you do is use quotes (single or double) for regex delimiters without the preceding "m" as the usual regex operator.
runrig
V good and simple, going to take the foreach answer as that's very handy for beginners.
Anthony
+2  A: 

if you have:

$a = "a:b:c:d";
@b = split /:/, $a;

then you get:

@b = ("a", "b", "c", "d")

In general, this is how split works:

split /PATTERN/,EXPR

Where PATTERN can be pretty much regex. You're not limited to simple tokens like ':'

Nathan Fellman
+2  A: 

Yes, split is what you want.

@tokens = split(/:/, "a:b:c:d");
foreach my $token (@tokens) {
    ....
}
Ryan Graham
foreach my $token (@tokens) {}my! my! my :)
Thanks. I normally use PHP for this stuff :-P
Ryan Graham
+3  A: 

Also take a look at the documentation that comes with perl by typing at a command line prompt:

perldoc -f split

To search the FAQs use

perldoc -q split