in reply to Function over all letters in a string

Dunno if it is simpler but...
$string =~ s/(.)/$1 x (1 + rand(3))/egs;

Replies are listed 'Best First'.
Re: Re: Function over all letters in a string
by Roger (Parson) on Dec 01, 2003 at 02:26 UTC
    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.
      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
        

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