http://www.perlmonks.org?node_id=512782


in reply to Elegant way to split into sequences of identical chars?

I know, obfuscated != elegant. Nevertheless, I thought it was kind of neat.
my $str = 'xx556xx'; my @x = grep --$|, $str =~ m/((.)\2*)/g; print join ',', @x;
The trick with $| is that it's a toggle, so grep throws away every other member of its input. The same thing could be done with a normal variable like so:
my $str = 'xx556xx'; my $tog = 0; my @x = grep $tog = !$tog, $str =~ m/((.)\2*)/g; print join ',', @x;
or using split:
my $str = 'xx556xx'; my $tog = 0; my @x = grep $tog = !$tog, split /(?<=(.))(?!\1)/, $str; print join ',', @x;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Elegant way to split into sequences of identical chars?
by bioMan (Beadle) on Nov 29, 2005 at 23:13 UTC

    I was fascinated by the use of the $| "output autoflush". I usually use '$| = 1;' or '++$|;' for the scripts I write on Windows. So I tried the same.

    my $str = 'xx556xx'; my @x = grep --$|, $str =~ m/((.)\2*)/g; my @y = grep ++$|, $str =~ m/((.)\2*)/g; print join ',', @x; print "\n"; print join ',', @y;

    The output being:

    xx,55,6,xx

    xx,x,55,5,6,6,xx,x

    I was somewhat suprised as all the documentation I've seen for '$|' says a non-zero value will force fflush after every 'write' or 'print' statement. I assumed the behavior would be the same for positive and negative values. What gives?

    Mike

      I've seen for '$|' says a non-zero value will force fflush after every 'write' or 'print' statement.
      For a better explanation, see the thread Perl Idioms Explained - $|++, especially where it talks about ++ and --.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of