in reply to Function over all letters in a string

What can be done with foreach can usually be done on fewer lines with map...

$string=join'',map{$_ x rand 8}split//,$string;

$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

Replies are listed 'Best First'.
Re: Re: Function over all letters in a string
by Roger (Parson) on Dec 01, 2003 at 06:04 UTC
    But you can not omit the (1 + rand ...) bit. Otherwise you will be dropping characters when the $_ x rand 8 bit evaluates to $_ x 0.

    my $string = "It's a cat and mouse game."; $string=join'',map{$_ x rand 3}split//,$string; print "$string\n"; $string = "It's a cat and mouse game."; $string=join'',map{$_ x (1 + rand 3)}split//,$string; print "$string\n";
    And the output -
    It'ss a caatt aannoouuss gaae It'''sss aa cccaaattt and mmmoussseee gggaaammee...

      Heh. I took things too literally, as is my tendency on occasion. I read "random number of letters" and assumed without further thought that zero is a perfectly cromulent random number. If you want a nonzero random number, then replace rand 8 with (1+rand 7). Vary the number 7 according to taste.


      $;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/