Pad a SAS macro variable with leading zeros

Another one of those handy reminders (posted in the hope that it will eventually make finding this information easier for myself and others who are equally inept at searching SAS documentation).

This is explained in the SAS knowledge base article How to add leading zeros on the index variable of a MACRO %DO loop.

The answer (unless you were programming in SAS from the moment you were born) is just as unintuitive as I have come to expect from SAS:

The PUTN function along with %SYSFUNC can be used to apply the Zw.d format to the value of I. The Zw.d format writes out standard numeric data with leading zeros.

%macro test;
  %do i=1 %to 100;
    %let val=%sysfunc(putn(&i,z3.));
    %put &val;
  %end;
%mend;

%test

I understand the miracle SAS was when it was first invented, but, seriously, would it really have hurt anything to include a sprintf like function in the macro language at some point.

You might ask, what kind of an idiot I am to be using SAS macros without knowing this kind of basic stuff.

The answer is, in the past two decades of using SAS, I have found the experience comparable to writing Fortran IV in the mid 80s — and if you think I liked it, you do not understand why I like C and Perl. My brain has developed a self-defense mechanism that immediately blocks SAS trivia from entering long term storage.

If I were doing this on a system with Perl, I would have actually avoided the SAS macro system entirely, and written a template using HTML::Template (it ain’t just for HTML).

Now, I shall slay all those tables with VAR01, VAR02, …, VARnn with a liberal sprinkling of & and %, I am close getting things done.