Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tokenise / tokenize / split a delimited string in Perl?

Tags:

split

token

perl

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

like image 579
Anthony Avatar asked Mar 18 '09 19:03

Anthony


People also ask

How do I split a string into a character in Perl?

If you need to split a string into characters, you can do this: @array = split(//); After this statement executes, @array will be an array of characters. split recognizes the empty pattern as a request to make every character into a separate array element.

How do I slice a string in Perl?

substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified.

How do I split a string with spaces in Perl?

Perl | split() Function. split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression(pattern), a group of characters or on undefined value etc..


2 Answers

Yes, split is what you want.

@tokens = split(/:/, "a:b:c:d");
foreach my $token (@tokens) {
    ....
}
like image 75
Ryan Graham Avatar answered Nov 15 '22 16:11

Ryan Graham


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


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

For more advanced parsing, I recommend Parse::RecDescent

like image 42
Geo Avatar answered Nov 15 '22 15:11

Geo