in reply to Re: Function over all letters in a string
in thread Function over all letters in a string

You might want to capture only letters instead.

my $string = "It's a cat and mouse game."; $string =~ s/(.)/$1 x (1 + rand(3))/ges; print "$string\n"; $string = "It's a cat and mouse game."; $string =~ s/([A-Za-z])/$1 x (1 + rand(3))/ges; print "$string\n";
And the output is -
IIIt'''s a cccat annddd mmoooussee gaammeee... IIItt'sss aa cccaaattt and mmoouusee ggaame.
Note that in the first case, spaces are multiplied too. But I thought the original question was to multiply letters only. ;-)

Update: Crossed out my comment. I agree I was too fussy on the 'technical correctness'. What's more important is not the code, but the idea that's behind it. And yes I like tilly's code too.

Replies are listed 'Best First'.
Re: Re: Re: Function over all letters in a string
by tilly (Archbishop) on Dec 01, 2003 at 02:29 UTC
    What do you define a letter to be?

    I found that part of the spec ambiguous and so made up a convenient definition. *shrug*

      I found that part of the spec ambiguous and so made up a convenient definition.
      You also apparently made a convenient definition of the phrase "random number". :)

      Personally, I'd like something that has a chance of producing a long string, but favouring shorter ones. Hence, a simple 1 + int rand 12 won't do. Rather, I'm tempted to use an exponential function:

      $_ = 'cat'; s/(.)/$1 x int(12**rand)/ge; print;
      Which, for example, prints
      caaatttttttt
      
        But that still puts an arbitrary (low) limit on the number of repetitions. The code below doesn't:
        #!/usr/bin/perl use strict; use warnings; $_ = 'cat'; s/(.)/my $t = $1; $t .= $1 while 0.95 > rand; $t/ge; print "$_\n"; __END__ cccccccccccccaaaaat

        Abigail

        You would have a larger range of possible numbers with:
        $string =~ s=(\w)= $1 x (1 - 1/log(rand)) =eg;
Re: Re: Re: Function over all letters in a string
by pg (Canon) on Dec 01, 2003 at 03:28 UTC

    Roger, I personally think that, it is easier to get the idea across, if the demo code has a clear focus.