On May 10, 3:53 am, [email protected] (Shlomi Fish) wrote:
> Hi Thomas,
>
> a few comments on your code.
>
> On Monday 10 May 2010 13:45:53 Thomas Bätzler wrote:
>
>
>
> > Finalfire <[email protected]> asked:
> > > Hello guys! I'm skilling regex using Perl and i've some trouble about
> > > a simple try:
> > > i've a string like:
>
> > > $string = "HELLOOOOAAABBCCCC";
>
> > > and i want to manipulate in that way: HELL4O3ABB4C;You can simply
> > > notice that when i have 3 or more occurrences of a character, i want
> > > to substitute all the occurrences and write "nC" where n is how times
> > > the character C is found on a string.
>
> > > So, in regex (i think there are so many way to do it but i wish to do
> > > with regex, just skilling...) i write:
>
> > > $string =~ s/(.)\1\1+/$1/;
>
> > > but how can i get the number of the occurrences in the string of that
> > > pattern?
>
> > #!/usr/bin/perl -w
>
> use warnings is preferable to the -w flag.
>
> > use strict;
>
> > my $string = "HELLOOOOAAABBCCCC";
>
> > print "$string\n";
>
> > $string =~ s/(.)\1{2,}/length($&).$1/eg;
>
> Please don't use $& as it slows down all subsequent regular expression matches
> considerably. See the warning about it on perldoc perlvar. Instead wrap up the
> entire match in an extra parentheses, like Shawn and I demonstrated.
>
Only a problem, if you're doing tons of regexes within the program
though.
Even better, as of 5.10, the /p switch and ${^PREMATCH}, ${^MATCH},
and ${^POSTMATCH} eliminate the penalty:
As a workaround for this problem, Perl 5.10.0 introduces "$
{^PREMATCH}",
"${^MATCH}" and "${^POSTMATCH}", which are equivalent to $`, $&
and $',
except that they are only guaranteed to be defined after a
successful
match that was executed with the "/p" (preserve) modifier. The use
of
these variables incurs no global performance penalty, unlike their
punctuation char equivalents, however at the trade-off that you
have to
tell perl when you want to use them.
--
Charles DeRykus
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/