Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string into only two parts with Perl?

Tags:

split

perl

I have a string that with several parts separated by tabs:

 Hello\t2009-08-08\t1\t2009-08-09\t5\t2009-08-11\t15

I want to split it up only on the first tab, so that "Hello" ends up in $k and and rest ends up in $v. This doesn't quite work:

my ($k, $v) = split(/\t/, $string);

How can I do that?

like image 824
biznez Avatar asked Sep 11 '09 18:09

biznez


People also ask

How do I split a string into multiple parts?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How do I split a string into multiple strings in Perl?

A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter. split syntax is: Split /pattern/, variableName.

How do you split a string in half?

We can split the strings into two halves by using the slice () constructor. We separate the first half and second half of the string and then save these halves in different variables.

What is chop in Perl?

The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character.


1 Answers

In order to get that, you need to use the 3rd parameter to split(), which gives the function a maximum number of fields to split into (if positive):

my($first, $rest) = split(/\t/, $string, 2);
like image 59
Chris Lutz Avatar answered Nov 15 '22 20:11

Chris Lutz