"...doesn't seem terribly elegant..."

Certainly AnnonyMonk's one-liner is more elegant, for many values of "elegant," but there's a certain elegance (IMO) to a step-by-step listing for future readers who may find the regex above a bit intimidating or even confusing.

So, inelegant though it may be (especially, "gentle, future-readers," the global variable declarations which you would do well to avoid in any substantial project), TIMTOWTDI:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # group adjacent-identical-chars to array elements; OP wanted "elegant +" rather than char-by-char like this my $str = '011122xx3x344444'; my @new_arr; my $last_seen = ''; my $found_char = ''; my $arr_element; while ($str =~ /([A-Z,0-9])/ig) { $found_char = $1; if ( $last_seen =~ /$found_char/ ) { $arr_element .= $found_char; } else { if ($found_char ) { push @new_arr, $arr_element; } $arr_element = $found_char; $last_seen = $found_char; } next; } push @new_arr, $arr_element; print Dumper @new_arr;<c> <p>which outputs:</p> <c>$VAR1 = '0'; $VAR2 = '111'; $VAR3 = '22'; $VAR4 = 'xx'; $VAR5 = '3'; $VAR6 = 'x'; $VAR7 = '3'; $VAR8 = '44444';

In reply to Re: Regex question by ww
in thread Regex question by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.