in reply to Pick a random string char with a regex
my $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; my ($random) = $string =~ m/(??{'.'x rand length $string })(.)/s; print $random, "\n";
------------
UPDATE1: And here it is without the dependancy on knowing the name of the scalar holding the string (Thanks perlre).
my $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; my( $random ) = $string =~ m/^(??{ '.' x rand length $_ })(.)/s; print "$random\n";
I knew there had to be a way. ;)
------------
UPDATE2: And here it is with a quantifier instead of a huge string of '.' metacharacters. The code is longer, but it's more friendly to real long target strings.
my $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; my ($random) = $string =~ m/^ (??{'.{' . int(rand length $_) . '}' }) (.) /sx; print "$random\n";
Enjoy!
Dave
|
|---|