Did
you know that: the REVERSE function can be very useful and also a lot of fun to
use?
The
REVERSE function can be used to return a character string in reverse
order. For instance, consider the
following example:
data testit;
x = "SAS";
Y = reverse(x);
put "x=
" x;
put "y=
" y;
run;
As
you can see from the log:
1 data testit;
2
3 x =
"SAS";
4 Y = reverse(x);
5
6 put "x= "
x;
7 put "y= "
y;
8
9 run;
x= SAS
y= SAS
…
Y is the exact reverse of X!
A
more practical application of this can be found when you need to pluck out the
last node in something, such as a full-path file name. Here is an example from a SAS program that I
use to get the name of previously executed SAS programs from the LOGFILE
variable in LOGPARSE SAS data sets:
/**********************************/
/* Determine the SAS program name */
/**********************************/
logtemp = reverse(strip(logfile));
r = index(logtemp,"\");
substr(logtemp,r,length(logtemp)
- r + 1) = "
";
SASprogram = tranwrd(strip(reverse(logtemp)),"log","sas");
In
the example, I know that logfile has the full path name of a SAS log, such
as: "c:\production\fy02\bigprog.log". If the name of the log is "bigprog.log", then the program
that was executed must be "bigprog.sas". That is what I want to capture in variable
SASprogram.
So,
the snippet of code first reverses LOGFILE, then looks for the first
"/", which was originally the last "/", but is now the first
one since the full path has been reversed.
It turns the rest of the contents of LOGTEMP into blanks. Then, it sets SASprogram equal to the strip-ed,
reverse (again) of LOGTEMP while translating "log" into "sas". Neat, clean, and effective!
Best
of luck in all your SAS endeavors!
---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the
new cult classic for computer programmers: It Only Hurts When I
Hit <ENTER>
Print edition: http://tinyurl.com/z8bzx2e
Kindle edition: http://tinyurl.com/zypgqa7
The hack above is an
excerpt from the book: Did
You Know That? Essential Hacks for Clever SAS Programmers
Print edition: http://tinyurl.com/z8bzx2e
Kindle edition: http://tinyurl.com/zypgqa7
No comments:
Post a Comment