Bxr MKH
Bxr MKH

Reputation: 131

How to split the data with splitting value?

How to split the data using by particular letter but the splitting data is present into the previous split ted line.

My perl code

$data ="abccddaabcdebb";
@split = split('b',"$data");
foreach (@split){
    print "$_\n";
}  

In this code gives the outputs but i expected outputs is:

ab
ccddaab
cdeb
b

How can i do this

Upvotes: 4

Views: 319

Answers (3)

ikegami
ikegami

Reputation: 385779

The first parameter of split defines what separates the elements you want to extract. b doesn't separate your elements you want since it's actually part of what you want.

You could specify the split after b using

my @parts = split /(?<=b)/, $s;

You could also use

my @parts = $s =~ /[^b]*b/g;

Side note:

split /(?<=b)/

splits

a b c b b

at three spots

a b|c b|b| 

so it results in four strings

  1. ab
  2. cb
  3. b
  4. Empty string

Fortunately, split removes trailing blank strings from its result by default, so it results in the three desired strings instead.

  1. ab
  2. cb
  3. b

Upvotes: 1

mpapec
mpapec

Reputation: 50637

You'll need positive look behind if you want to include letter b as delimiter is excluded from resulting list.

my $data ="abccddaabcdebb";
my @split = split(/(?<=b)/, $data);
foreach (@split) {
    print "$_\n";
}  

From perldoc -f split

Anything in EXPR that matches PATTERN is taken to be a separator that separates the EXPR into substrings (called "fields") that do not include the separator.

Upvotes: 2

jh314
jh314

Reputation: 27792

You can use lookbehind to keep the b:

$data ="abccddaabcdebb";
@split = split(/(?<=b)/, $data);    
foreach (@split){
    print "$_\n";
}  

will print out

ab
ccddaab
cdeb
b

Upvotes: 3

Related Questions