"...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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |