String::Random - Perl module to generate random strings based on a pattern
| Use Case | Command | Description |
|---|---|---|
| π Generate random password from pattern | $gen->randpattern("CCcc!ccn") | Mixed case, punctuation, digit |
| π² Generate random string from regex | $gen->randregex('\d\d\d') | 3 random digits |
| π Use secure random generation | String::Random->new(rand_gen => \&secure_sub) | Specify custom RNG |
| β Add custom pattern | $gen->set_pattern('A' => ['A'..'Z','a'..'z']) | Define new character class |
| β‘ Procedural interface (no object) | random_string("...") | Generate string from pattern |
version 0.32
use String::Random;
my $string_gen = String::Random->new;
print $string_gen->randregex('\d\d\d'); # Prints 3 random digits
# Prints 3 random printable characters
print $string_gen->randpattern("...");
or
use String::Random qw(random_regex random_string);
print random_regex('\d\d\d'); # Also prints 3 random digits
print random_string("..."); # Also prints 3 random printable characters
This module makes it trivial to generate random strings.
As an example, let's say you are writing a script that needs to generate a random password for a user. The relevant code might look something like this:
use String::Random;
my $pass = String::Random->new;
print "Your password is ", $pass->randpattern("CCcc!ccn"), "\n";
This would output something like this:
Your password is UDwp$tj5
β οΈ NOTE: currently, "String::Random" defaults to Perl's built-in predictable random number generator so the passwords generated by it are insecure. See the "rand_gen" option to "String::Random" constructor to specify a more secure random number generator. There is no equivalent to this in the procedural interface, you must use the object-oriented interface to get this functionality.
If you are more comfortable dealing with regular expressions, the following code would have a similar result:
use String::Random;
my $pass = String::Random->new;
print "Your password is ",
$pass->randregex('[A-Z]{2}[a-z]{2}.[a-z]{2}\d'), "\n";
The pre-defined patterns (for use with randpattern() and random_pattern()) are as follows:
c β Any Latin lowercase character [a-z]C β Any Latin uppercase character [A-Z]n β Any digit [0-9]! β A punctuation character [~`!@$%^&*()-_+={}[]|\:;"'.<>?/#,]. β Any of the aboves β A "salt" character [A-Za-z0-9./]b β Any binary dataThese can be modified, but if you need a different pattern it is better to create another pattern, possibly using one of the pre-defined as a base. For example, if you wanted a pattern "A" that contained all upper and lower case letters ("[A-Za-z]"), the following would work:
my $gen = String::Random->new;
$gen->{'A'} = [ 'A'..'Z', 'a'..'z' ];
or
my $gen = String::Random->new;
$gen->{'A'} = [ @{$gen->{'C'}}, @{$gen->{'c'}} ];
or
my $gen = String::Random->new;
$gen->set_pattern(A => [ 'A'..'Z', 'a'..'z' ]);
The random_string function, described below, has an alternative interface for adding patterns.
new
new max => *number* new rand_gen => *sub*
Create a new String::Random object.
Optionally a parameter "max" can be included to specify the maximum number of characters to return for "*" and other regular expression patterns that do not return a fixed number of characters.
Optionally a parameter "rand_gen" can be included to specify a subroutine coderef for generating the random numbers used in this module. The coderef must accept one argument "max" and return an integer between 0 and "max - 1". The default rand_gen coderef is
sub {
my ($max) = @_;
return int rand $max;
}
randpattern LIST
The randpattern method returns a random string based on the concatenation of all the pattern strings in the list.
It will return a list of random strings corresponding to the pattern strings when used in list context.
randregex LIST
The randregex method returns a random string that will match the regular expression passed in the list argument.
Please note that the arguments to randregex are not real regular expressions. Only a small subset of regular expression syntax is actually supported. So far, the following regular expression elements are supported:
\w β Alphanumeric + "_".\d β Digits.\W β Printable characters other than those in \w.\D β Printable characters other than those in \d.. β Printable characters.[] β Character classes.{} β Repetition.* β Same as {0,}.? β Same as {0,1}.+ β Same as {1,}.get_pattern STRING
Return a pattern given a name.
my $gen = String::Random->new;
$gen->get_pattern('C');
(Added in version 0.32.)
set_pattern STRING ARRAYREF
Add or redefine a pattern given a name and a character set.
my $gen = String::Random->new;
$gen->set_pattern(A => [ 'A'..'Z', 'a'..'z' ]);
(Added in version 0.32.)
from_pattern
IGNORE! - for compatibility with an old version. DO NOT USE!
random_string PATTERN,LIST
random_string PATTERN
When called with a single scalar argument, random_string returns a random string using that scalar as a pattern. Optionally, references to lists containing other patterns can be passed to the function. Those lists will be used for 0 through 9 in the pattern (meaning the maximum number of lists that can be passed is 10). For example, the following code:
print random_string("0101",
["a", "b", "c"],
["d", "e", "f"]), "\n";
would print something like this:
cebd
random_regex REGEX_IN_STRING
Prints a string for the regular expression given as the string. See the synopsis for example.
This is Bug Freeβ’ code. (At least until somebody finds oneβ¦)
Please report bugs here:
https://rt.cpan.org/Public/Dist/Display.html?Name=String-Random
Original Author: Steven Pritchard steve AT silug.org
Now maintained by: Shlomi Fish ( http://www.shlomifish.org/ ).
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
Please report any bugs or feature requests by email to "bug-string-random at rt.cpan.org", or through the web interface at https://rt.cpan.org/Public/Bug/Report.html?Queue=String-Random. You will be automatically notified of any progress on the request by the system.
The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)
https://github.com/shlomif/string-random
git clone http://github.com/shlomif/String-Random
Shlomi Fish shlomif AT cpan.org
Please report any bugs or feature requests on the bugtracker website https://github.com/shlomif/string-random/issues
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
This software is copyright (c) 2021 by Shlomi Fish.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-17 18:50 @216.73.216.176
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)