tags:

views:

454

answers:

3

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?

+9  A: 

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);
Chris Lutz
What if the value's length is uncertain, and I want to capture all of it in $v. $v's format is going to look like date_1\tvalue_1\tdate_2\tvalue_2\tdate_3\tvalue_3...
biznez
This will capture "date_1" in $k, and "value_1\tdate_2\tvalue_2\tdate_3\tvalue_3..." in $v. For more information, I linked to the perldoc reference page on the `split()` function - it will explain how it works in all the detail you could ever want. I suggest you read it. Perldoc is very informative.
Chris Lutz
+3  A: 

No. It will give you the first two items and toss the rest. Try this:

my ($k, $v) = split(/\t/, $string, 2);
jbourque
What if the value's length is uncertain, and I want to capture all of it in $v. $v's format is going to look like date_1\tvalue_1\tdate_2\tvalue_2\tdate_3\tvalue_3...
biznez
Like Chris Lutz said in his comment, the number tells Perl how many parts to split into. So, with a value of 2, the first part goes in $v, the first \t in consumed in the split, and the remainder of the string goes unaltered into $v.
jbourque
A: 

Another option would be to use a simple regex.

my($k,$v) = $str =~ /([^\t]+)\t(.+)/;
Brad Gilbert