vkk05
vkk05

Reputation: 3222

Perl split the string and print separator too

I have a string and splitting with respect to colon(:) or semicolon(;) followed by space.

Here is code snippet.

my $string = "MAJOR RCB_Board: Circuit Disconnected";

my ($rest, $text) = split(/;|:\s+/, $string);
print "Rest=$rest ** Text=$text\n";

But here I want to print split separator also with the string. In this example (:).

So I should get output like below:

Rest=MAJOR RCB_Board: ** Text=Circuit Disconnected

Upvotes: 0

Views: 68

Answers (1)

Georg Mavridis
Georg Mavridis

Reputation: 2331

You can catch (part) of the separator by putting it into parentheses.

e.g. :

my $string = "MAJOR RCB_Board: Circuit Disconnected";

my ($rest, $separator, $text) = split(/(;|:)\s+/, $string);
print "Rest=$rest$separator ** Text=$text\n";

Upvotes: 1

Related Questions