Portrait of Michael Limberger

Michael Limberger

Need me? Email mike@limberger.ca

Perl

Self-modifying code

A script that keeps score by editing itself

2024-06-25

This note is about self-modifying Perl. Not as a party trick for its own sake, but as a way to understand how flexible the language still is when you need it.

#!/usr/bin/env perl
use feature 'say';

say "Count: 0";

$/=undef;
my $self = do { local @ARGV = ($0); <> };
$self =~ s~Count: \\K\\d+~$& + 1~e;
@ARGV = ($0);
$^I = qq|.${\\time}.bak|;
say $self while <>;

First run prints Count: 0, then the file says Count: 1. Next run prints 1. The source on disk is the scoreboard. Timestamped .bak files are the history.

The surgery

$/Set to undef: slurp the whole file.
$0This script's name.
\KKeep: only the digits land in $&.
$^IIn-place edit, with a backup suffix.
Party trick, not a ship item. Version control hates it. One bug corrupts the source. The useful neighbour is $^I plus @ARGV for real in-place tools.