Skip to content

Instantly share code, notes, and snippets.

@adokoy001
Created May 19, 2021 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adokoy001/76520b6027418dafabd78dabf252d33b to your computer and use it in GitHub Desktop.
Save adokoy001/76520b6027418dafabd78dabf252d33b to your computer and use it in GitHub Desktop.
Random string generator
#!/usr/bin/env perl
use strict;
use warnings;
my $length = shift // 64;
my $mode = shift // 'default'; # alphabet,small,capital,number,complex
my @special_chars = ('_','-','?','=','^','[',']','{','}','&','$','#','@','!','*','~','`','%','(',')','+','|',':',';','"',"'",'<','>',',','.','/','\\');
my @small_chars = ('a' .. 'z');
my @capital_chars = ('A' .. 'Z');
my @number_chars = (0 .. 9);
my @chars;
if($mode eq 'alphabet'){
@chars = (@small_chars,@capital_chars);
}elsif($mode eq 'small'){
@chars = (@small_chars);
}elsif($mode eq 'capital'){
@chars = (@capital_chars);
}elsif($mode eq 'number'){
@chars = (@number_chars);
}elsif($mode eq 'complex'){
@chars = (@number_chars,@number_chars,@number_chars,@capital_chars,@small_chars,@special_chars);
}else{
if($mode ne 'default'){
print "Given option '$mode' is invalid.\n";
}
@chars = (@number_chars,@number_chars,@number_chars,@capital_chars,@small_chars);
}
@chars = &shuffle(@chars);
my $output = '';
if($mode eq 'complex'){
my @tmp_array;
push(@tmp_array,$special_chars[int(rand($#special_chars+1))]);
push(@tmp_array,$small_chars[int(rand($#small_chars+1))]);
push(@tmp_array,$capital_chars[int(rand($#capital_chars+1))]);
push(@tmp_array,$number_chars[int(rand($#number_chars+1))]);
for(1 .. $length - 4){
my $tmp = $chars[int(rand($#chars+1))];
push(@tmp_array,$tmp);
}
@tmp_array = &shuffle(@tmp_array);
$output = join('',@tmp_array);
}else{
for(1 .. $length){
my $tmp = $chars[int(rand($#chars+1))];
$output = $output . $tmp;
}
}
print "> $output\n";
sub shuffle (@) {
my @a=\(@_);
my $n;
my $i=@_;
map {
$n = rand($i--);
(${$a[$n]}, $a[$n] = $a[$i])[0];
} @_;
}
@adokoy001
Copy link
Author

adokoy001 commented May 19, 2021

I use this script when I need some random strings.

How to use this:
with alias "rand=/home/myname/perlscripts/gen_rand.pl",

$ rand 12 complex
> i2b89(%-XRR-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment