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?
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.
A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter. split syntax is: Split /pattern/, variableName.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With