How to ROT13 encode text using perl -pe?
Question
How to ROT13 encode text using perl -pe?
Using perl -pe for ROT13 encoding is a classic and elegant example showcasing Perl’s powerful text processing capabilities. ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. Because the English alphabet has 26 letters, applying ROT13 twice returns the original text.
What is perl -pe?
The perl -pe command line flag runs Perl with a loop around your program that reads line by line from standard input, executes the code you provide with -e, and then prints each processed line. This makes it perfect for quick text transformations like ROT13.
How to ROT13 encode using perl -pe
You can use Perl’s transliteration operator tr/// to implement ROT13. The tr/// operator replaces specified characters with other characters in the same string—and it works in place.
Since ROT13 substitutes letters A–Z and a–z with letters 13 positions down the alphabet, the syntax is:
tr/A-Za-z/N-ZA-Mn-za-m/
Here, the first part A-Za-z matches all uppercase and lowercase letters, and the second part N-ZA-Mn-za-m specifies the ROT13-mapped letters.
Complete example:
perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/'
You can test it by echoing a string and piping it to this Perl one-liner. For example:
echo "Hello, World!" | perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/'
This will output:
Uryyb, Jbeyq!
Explanation:
-p: Loop over each line of input, applying your code, then print the line automatically.-e: Allows specifying a Perl program directly on the command line.tr///: Transliterate each letter according to ROT13.
Common pitfalls
- Make sure to include both uppercase
A-Zand lowercasea-zranges intr///, or letters outside these will be unchanged. - Using
-pemeans Perl processes one line at a time, so it preserves line endings automatically. - If you want to decode ROT13 from a file, just replace the input or use redirection, for example:
perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/' file.txt.
Version notes
This one-liner uses core Perl functionality that has existed since Perl 4. No special modules or features needed—so it works across all modern Perl versions, including Perl 5.x.
Summary
ROT13 is straightforward in Perl with transliteration. Using perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/' gives you a very compact, efficient encoder conveniently usable from the command line for any text input.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 118ms
(empty)(empty)Was this helpful?
Related Questions
- How to print matching groups from regex with perl -ne?
- How to generate random password using perl -e?
- How to convert hex to decimal with perl one-liner?
- How to trim whitespace from lines using perl -pe?
- How to shuffle lines randomly with perl one-liner?
- How to print every Nth line with perl one-liner?