HOWTO: Create a random alpha-numeric string in Perl

Creating an alpha-numeric string in Perl is easy, but having a quick function you can call is better!

This is very useful for things like password generators.

To see how to do this in Python, check out this post: …howto-create-a-random-alpha-numeric-string-in-python

To see how to do this in PHP, check out this post: …howto-create-a-random-alpha-numeric-string-in-php

sub makeID {
    my $makeIDchars = ( $#_ >= 0 ? shift @_ : 6);
    my @makeIDpool = ('a'..'z','A'..'Z',0..9);
    return join '', map $makeIDpool[int(rand($#makeIDpool - 1))], 1..$makeIDchars;


This code sample:

print makeID()."\n";
print makeID(10)."\n";
print makeID(20)."\n";
print makeID(1)."\n";

Will print something like this:


Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, perl, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *