Typewriter Using Regex Substitution

By: w1ldc4rd-w1z4rd
[ BACK... ]

Ever wondered how to add a touch of retro flair to your Perl scripts? Today, we’re diving into a clever technique that simulates the nostalgic charm of an old-school typewriter using Perl’s regex substitution. Let’s break down this nifty script and explore its key elements.

First, let’s look at the full code:

++;

my $text = <<'TYPE';
Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men
Couldn't put Humpty together again.
TYPE

typeWriter($text);

sub typeWriter($)
{
    my $text = shift;
    $text =~ s`.`
        select(undef, undef, undef, rand(0.05)); 
        print ;
    `sger;   
}

Now, let’s unpack the key elements:

Autoflush

++;

This line enables autoflush on STDOUT, ensuring each character prints immediately rather than being buffered.

Here-doc

my $text = <<'TYPE';
# ... text ...
TYPE

We use a here-doc to create a multi-line string.

Function Declaration

sub typeWriter($)

This declares our typeWriter function. The ($) prototype indicates it expects one scalar argument.

Regex Substitution Magic

$text =~ s`.`
    select(undef, undef, undef, rand(0.05)); 
    print ;
`sger;

This is where the typewriter effect happens. We’re using Perl’s regex substitution in an unconventional way:

This creative use of regex substitution allows us to process each character individually, adding a delay and printing it to create the typewriter effect.

In essence, we’re repurposing Perl’s text processing capabilities to create a visual effect. It’s a prime example of Perl’s flexibility and the “There’s More Than One Way To Do It” philosophy.

Copyright ©️ 2024 perl.gg