in reply to Regex to replace consecutive tokens

{}think:

Yet another way to do it:

$s = join(",", map {$_ ne '' ? $_ : '0'} split /,/,$s,-1);

Update: Added '-1' to split to ensure we don't lose trailing commas, as hdb mentions. (Also corrected typo $t-->$s.)

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Regex to replace consecutive tokens
by hdb (Monsignor) on Oct 18, 2013 at 13:24 UTC

    This way you will lose all trailing commas...

    $s="1,2,3,,5,6,,,9,10,,,,14,15,,,,,,,,,,,,,,," will turn into $s="1,2,3,0,5,6,0,0,9,10,0,0,0,14,15".

      Easy to fix:
      my $t = '1,2,3,,5,6,,,9,10,,,,14,15,,,,,,,,,,,,,,,'; my $s = join ',' => map { $_ ne '' ? $_ : '0' } split /,/ => $t, 1 + $t =~ y/,//;

      Update: Or, maybe a bit more readable

      my $s = join ',' => map $_ || 0, split /,/ => $t, 1 + $t =~ y/,//;
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ