Reputation: 815
I am trying to split a string in Perl such as below :-
String = "What are you doing these days?"
Split1 - What
Split2 - are
Split3 - you
Split4 - doing these days?
I want the first n number of words separately and the rest of the line together in a separate variable.
Is there any way to do this ? There is no common delimiter I can use. Any help is appreciated ! Thanks.
Upvotes: 0
Views: 371
Reputation: 98508
Perl's split has a limit parameter that seems to be just what you want. To split off the first $n words and leave the rest together, use $n+1 as the limit (the result will be at most $n+1 elements):
my $n = 3;
my $string = "What are you doing these days?";
my @words = split / /, $string, $n+1;
print "$_\n" for @words;
Upvotes: 7
Reputation: 3967
You can use the following regex to split the string according to your requirement
$ip_tring = "What are you doing these days?";
if($ip_tring =~ m/(\S+)\s(\S+)\s(\S+)\s(.*)/)
{
print("1=$1,2=$2,3=$3,4=$4\n");
}
else
{
print("no match...\n");
}
Upvotes: 0