Inside-out loops

This is a silly post. I am going to show you a contrived example of Perl code that is emulating what 8-bit assembler code does to loop through a 16-bit value. Why?

I have an ongoing researching project involving the Atari 2600 Video Console System, which has a MOS 6502 microcontroller at its heart. Assembler is not my native tongue and it helps to unpack these squirrelly bits into Perl to verify my understanding.

In a larger sense, though, seeing other ways to implement common tasks is salutary. If nothing else, you may appreciate how much lift you get from using higher level languages.

Anyway, the code:

my ($MAX_X, $MAX_Y) = (256, 256);
my ($x, $y) = (0, $MAX_Y);
printf("%-3d", $y);

   $x = $MAX_X;

   $x -= 1;
   printf("\t%-3d\n", $x);
   goto DEC_X if $x;

   print "-----------\n";
   $y -= 1;
   printf("%-3d", $y);
   goto RELOAD_X if $y;

print "\ndone\n";

This code essentially decrements the least significant byte ($x) until it is zero. It then decrements the most significant byte ($y). If $y is greater than zero, the program reloads $x to the maximum value begins decrementing it to zero again. The program ends when $y is zero.

No loop directives. No subroutines. Just goto spaghetti.

You're welcome.

Leave a comment

About Joe Johnston

user-pic I blog about Perl and related technologies primarily from a webdev perspective.