phpman > perldoc > String::Random(3pm)

Markdown | JSON | MCP    

NAME
    String::Random - Perl module to generate random strings based on a pattern

VERSION
    version 0.32

SYNOPSIS
        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

DESCRIPTION
    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";

  Patterns
    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 above
      s        A "salt" character [A-Za-z0-9./]
      b        Any binary data

    These 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.

  Methods
    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,}.

            Regular expression support is still somewhat incomplete. Currently special characters
            inside [] are not supported (with the exception of "-" to denote ranges of characters).
            The parser doesn't care for spaces in the "regular expression" either.

    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!

  Functions
    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 synposis for
            example.

BUGS
    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> .

AUTHOR
    Original Author: Steven Pritchard "steve AT silug.org"

    Now maintained by: Shlomi Fish ( <http://www.shlomifish.org/> ).

LICENSE
    This program is free software; you can redistribute it and/or modify it under the same terms as
    Perl itself.

SEE ALSO
    perl(1).

SUPPORT
  Websites
    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.

    *   MetaCPAN

        A modern, open-source CPAN search engine, useful to view POD in HTML format.

        <https://metacpan.org/release/String-Random>

    *   RT: CPAN's Bug Tracker

        The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.

        <https://rt.cpan.org/Public/Dist/Display.html?Name=String-Random>

    *   CPANTS

        The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

        <http://cpants.cpanauthors.org/dist/String-Random>

    *   CPAN Testers

        The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN
        distributions.

        <http://www.cpantesters.org/distro/S/String-Random>

    *   CPAN Testers Matrix

        The CPAN Testers Matrix is a website that provides a visual overview of the test results for
        a distribution on various Perls/platforms.

        <http://matrix.cpantesters.org/?dist=String-Random>

    *   CPAN Testers Dependencies

        The CPAN Testers Dependencies is a website that shows a chart of the test results of all
        dependencies for a distribution.

        <http://deps.cpantesters.org/?module=String::Random>

  Bugs / Feature Requests
    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.

  Source Code
    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

AUTHOR
    Shlomi Fish <shlomif AT cpan.org>

BUGS
    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.

COPYRIGHT AND LICENSE
    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.

String::Random(3pm)
NAME VERSION SYNOPSIS DESCRIPTION
Patterns Methods Functions
BUGS AUTHOR LICENSE SEE ALSO
perl(1).
SUPPORT
Websites Source Code
AUTHOR BUGS COPYRIGHT AND LICENSE

Generated by phpman v3.7.12 Author: Che Dong Under GNU General Public License
2026-06-13 14:39 @216.73.216.28
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 TransitionalValid CSS!

^_back to top