one-liners intermediate
How to generate random password using perl -e?
Question
How to generate random password using perl -e?
Generating a random password using Perl directly from the command line is a neat trick to quickly produce secure strings without writing full scripts. Perl’s flexibility and context sensitivity allow concise yet powerful one-liners.
Key Concepts
rand: Produces a fractional random number between 0 and the given range.int: Converts fractional numbers to integers, crucial for array indexing.- Arrays and sigils:
@for arrays like@charsand$for scalar elements like$chars[0]. - List context:
mapruns a block multiple times, generating a list for password characters.
The general approach is to build a character set, then pick random characters by index to form the password.
Runnable Perl Example (12-char Alphanumeric Password)
#!/usr/bin/env perl
use strict;
use warnings;
my @chars = ('A'..'Z', 'a'..'z', 0..9);
my $password = join '', map { $chars[int rand @chars] } 1..12;
print "$password\n";
Explanation:
@charscombines uppercase, lowercase letters, and digits.int rand @charspicks a valid random index into@chars.map { ... } 1..12repeats the random selection 12 times, producing 12 characters.join ''concatenates characters into a password string.printoutputs the password with a newline.
Important Perl Details and Best Practices
- Using
intaroundrandavoids fractional indices which would cause warnings or errors. - Perl’s scalars (variables starting with
$) hold single values, e.g., an element from@chars. - The
mapfunction in list context creates a list from repeated evaluations, ideal for generating password characters. - Using
use strictanduse warningsenables good coding hygiene and helps catch mistakes early.
Common Pitfalls
- Not wrapping
randwithintcan yield non-integer indices causing unexpected behavior. - Incorrect quoting or command-line flag ordering often causes syntax errors in one-liners.
- Using shell special characters in passwords requires careful escaping or alternative approaches.
- When running inline with
perl -e, avoid ending scripts with a trailing semicolon or quote errors.
Summary
This example is portable, simple, and runs safely without any external modules or file/network accesses—ideal for sandboxed environments. Extend @chars with symbols or adjust the repeat count in map to control password complexity and length.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 20ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
m7AYrE5VuNnD
STDERR
(empty)