On Fri, 3 Mar 2000, Bret Hughes wrote:

> looks like compression to me and DD < D!2
> 
> :)
> 
> Bret
> 
> Brian wrote:
> > 
> > On Fri, 3 Mar 2000, ::--Koshy Kerteya--~!~ wrote:
> > 
> > > Hi,
> > >
> > > Suppose I have a string of "AAAABCCCDD"
> > > And I wanna use perl to convert this to A!4BC!3DD
> > > what should I do ?
> > > Is there a ready function (grep???) to achieve this ?
> > 
> > yes perl can do this.
> > 
> > their is no built in function to just magically transform as you have
> > above.  It would take a little code.   Why is it:
> > 
> > AAAABCCCDD      A!4BC!3DD
> > and not
> > AAAABCCCDD      A!4BC!3D!2
> > 
> > I mean if its 1 character, just print it, if its two chars just print it?
> > then if its more than 2 do the char!num thing?
> > 


How about:
#!/usr/bin/perl

if($_[0] ne "")
{
    $Instring=$_[0];
}
else
{
    $Instring="AAAABCCCDD";
}

print("Instring is [$Instring]\n");

while($Instring =~ /(.)(\1{2,})/)
{
    $Original=$1.$2;
    $Replacement=$1.'!'.length($Original);
    print("Replacing [$Original] with [$Replacement]\n");
    $Instring =~ s/$Original/$Replacement/g;
}
print("Outstring is [$Instring]\n");


Instring is [AAAABCCCDD]
Replacing [AAAA] with [A!4]
Replacing [CCC] with [C!3]
Outstring is [A!4BC!3DD]


The magic is in the /(.)(\1{2,})/, which says "match any character, store
it in $1 and \1.  Then match two or more of the character you matched in
\1".

You could probably do it in one line.  If you man perlre, there's a way to
evaluate an expression within an re.  If you use this, you can evaluate
the length of the original string right in the re, and do an s/ instead of
an /.  However, I'm currently getting paid for actually doing work the
company asked me to work on, so I think I'm gonna leave it at that.


-- 
To unsubscribe: mail [EMAIL PROTECTED] with "unsubscribe"
as the Subject.

Reply via email to