Did Perl break a string into a repeating pattern in the most efficient way?

I would like to split a string that has a specific repeating pattern, for example:

$string = "GGGGG-SOMETHING-ELSE-GGG-LAST"; 

to

 @array=(-SOMETHING-ELSE-,-LAST); 

my attempt as perl newbie

 split(/G{2,}/,$string); 

Unfortunately, this leads to the fact that only GG templates are split, and not the greedy GGGGG or GGG templates, which I hoped for the result as a result of creating 2 array elements.

+4
source share
2 answers

No, it seems (mostly) to be the job as intended. The following code:

 use strict; use warnings; $_="GGGGG-SOMETHING-ELSE-GGG-LAST"; my @a=split(/G{2,}/,$_); print join(",",@a) . "\n"; 

outputs the result:

 ,-SOMETHING-ELSE-,-LAST 

The problem is that the first element of the empty string exists. So, to fix this, you can do something like:

 use strict; use warnings; $_="GGGGG-SOMETHING-ELSE-GGG-LAST"; my @a=grep{$_ ne ""}(split(/G{2,}/,$_)); print join(",",@a) . "\n"; 

And this creates what you want:

 -SOMETHING-ELSE-,-LAST 
+5
source

I just checked your code on my machine and it works great:

 $string = "GGGGG-SOMETHING-ELSE-GGG-LAST"; print join(':', split(/G{2,}/,$string)); 

returns:

 :-SOMETHING-ELSE-:-LAST 

Perl version I'm using: v5.10.1

Could you add more information on how you use it?

0
source

Source: https://habr.com/ru/post/1393048/


All Articles