in reply to randomizing global replacement

You left the /e off the regex:

use strict; use warnings; my @a = ('b' .. 'j'); my $str = 'a' x 23; $str =~ s/a/$a[rand@a]/ge; print "$str\n";

Prints:

dbjgcegjgieigecihebhdih

Oh, and don't use $a as a general purpose variable - it's magical ;)


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: randomizing global replacement
by lokiloki (Beadle) on Jan 30, 2007 at 04:15 UTC
    Thank you.

    Incidentally, the use of rand@a is something I have never seen before. My version of the Programming Perl book makes no mention of such usage of this as an alternative to $a[int(rand(@a))]... when did this alternative come into being?

      rand@a is just rand(@a) without the optional (). @ can't be part of the word beginning "rand", because it isn't a valid identifier character, so it's treated as a new token. The int() isn't necessary since array elements are automatically int'd (e.g. $a[3.14] automatically gets you $a[3]).

        I did consider putting a space in (rand @a), but decided that was making it too easy. Besides, the OP didn't use much white space so I was just being consistent. :D


        DWIM is Perl's answer to Gödel