Regex Typewriter
Welcome to one of my favorite Perl tricks - creating a typewriter effect using nothing but regex substitution! This technique demonstrates the incredible power of Perl's regex engine when combined with code evaluation.Part 1: THE SETUP - AUTOFLUSH
Before we get to the magic, we need to make sure output appears immediately. Normally Perl buffers output, which would ruin our typewriter effect.This cryptic incantation sets the output autoflush flag. Without it, your typewriter would type in chunks rather than character by character. The ++ just sets it to a true value (1).$|++;
Part 2: THE MAGIC REGEX
Here's where the real wizardry happens:Let me break this down piece by piece, because there's a lot happening here.$text =~ s`.` select(undef, undef, undef, rand(0.05)); print $& `sger;
Part 3: THE PATTERN - MATCHING EVERYTHING
The pattern is simply. - a single dot. In regex, this matches any single
character. But wait, there's more! See that s modifier at the end? That's
crucial.
Withouts - Makes . match newlines too (normally it doesn't) g - Global matching - process EVERY character e - Evaluate the replacement as Perl code r - Return the result instead of modifying in-place
s, your text would pause awkwardly at line breaks. With it, even
newlines get the typewriter treatment.
Part 4: THE REPLACEMENT - CODE AS TEXT
Thee flag is where Perl gets magical. Instead of a literal replacement
string, we're running actual code for each match:
The select() call is a sneaky way to sleep for a fraction of a second. Using rand(0.05) gives us a random delay between 0 and 50 milliseconds, creating that authentic mechanical typewriter feel - some keys faster, some slower.select(undef, undef, undef, rand(0.05)); print $&
The $& variable holds whatever the regex just matched - in our case, one character at a time. We print it, pause, print the next, pause...
Part 5: PUTTING IT ALL TOGETHER
Here's a complete working example:Run it and watch your text appear character by character with realistic timing variations. It's mesmerizing!#!/usr/bin/perl use ; use ; $|++; # Autoflush! my $text = "Hello, world!\nThis is a typewriter effect.\n"; $text =~ s`.` select(undef, undef, undef, rand(0.05)); print $& `sger;
Part 6: WHY THE BACKTICKS?
You might have noticed I used backticks as the regex delimiter instead of the usual forward slashes. This is purely stylistic - when your replacement contains a lot of code, using different delimiters can make things more readable. Perl lets you use almost any paired characters as delimiters.These are all equivalent:
Pick whatever makes your code clearest!s/pattern/replacement/ s`pattern`replacement` s{pattern}{replacement} s|pattern|replacement|
This technique showcases what makes Perl special - the ability to blur the line between data and code, between matching and transforming. A simple regex becomes a complete animation system.
Happy typing!
Created By: Wildcard Wizard. Copyright 2026