Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Elegant way to split into sequences of identical chars?

by Roy Johnson (Monsignor)
on Nov 29, 2005 at 21:53 UTC ( [id://512782]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://512782]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-24 04:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found