Basic Macro Processing Prepared by Destiny Corporation

Similar documents
Acknowledgments xi Preface xiii About the Author xv About This Book xvii New in the Macro Language xxi

Macro Quoting: Which Function Should We Use? Pengfei Guo, MSD R&D (China) Co., Ltd., Shanghai, China

SAS Macro Language: Reference

SAS Macro. SAS Training Courses. Amadeus Software Ltd

Going Under the Hood: How Does the Macro Processor Really Work?

Introduction. Getting Started with the Macro Facility CHAPTER 1

Sandra Hendren Health Data Institute

Foundations and Fundamentals. SAS System Options: The True Heroes of Macro Debugging Kevin Russell and Russ Tyndall, SAS Institute Inc.

title1 "Visits at &string1"; proc print data=hospitalvisits; where sitecode="&string1";

SAS Programming Techniques for Manipulating Metadata on the Database Level Chris Speck, PAREXEL International, Durham, NC

/ * %STR(argument) %NRSTR(argument)

Macro Internals for the User Developer s Overview. Susan O Connor, SAS Institute Inc., Cary, NC

Merge Processing and Alternate Table Lookup Techniques Prepared by

SAS Certification Handout #11: Adv. Prog. Ch. 9-10

Program Validation: Logging the Log

Advanced Macro Topics Steven First, Systems Seminar Consultants, Madison, WI

DSCI 325: Handout 15 Introduction to SAS Macro Programming Spring 2017

An Animated Guide: An Introduction to SAS Macro Quoting Russ Lavery Bryn Mawr, PA

Reading and Writing Data from Microsoft Excel/Word Using DDE

AN INTRODUCTION TO MACRO VARIABLES AND MACRO PROGRAMS Mike Zdeb, School of Public Health

CHAPTER 7 Using Other SAS Software Products

Macro Language Dictionary

Introduction to the SAS Macro Facility

SAS 101. Based on Learning SAS by Example: A Programmer s Guide Chapter 21, 22, & 23. By Tasha Chapman, Oregon Health Authority

Why & How To Use SAS Macro Language: Easy Ways To Get More Value & Power from Your SAS Software Tools

Base and Advance SAS

SAS Macro Programming for Beginners

An Introduction to Macros Deb Cassidy

Alias Macros, a Flexible Versioning System for Standard SAS Macros

Don't quote me. Almost having fun with quotes and macros. By Mathieu Gaouette

SAS Macro Dynamics - From Simple Basics to Powerful Invocations Rick Andrews, Office of the Actuary, CMS, Baltimore, MD

I like macros. But sometimes they can be hard to understand.

Advanced SQL Processing Prepared by Destiny Corporation

Dequote me on that: Using the dequote function to add some friendliness to SAS macros

The SAS Interface to REXX

New Macro Features Added in SAS 9.3 and SAS 9.4

An Introduction to SAS Macros

More About SAS Macros

Surviving the SAS Macro Jungle by Using Your Own Programming Toolkit Kevin Russell, SAS Institute Inc., Cary, North Carolina

Understanding the Concepts and Features of Macro Programming 1

SAS Macros Advanced Techniques

Macro Facility. About the Macro Facility. Automatic Macro Variables CHAPTER 14

Using an ICPSR set-up file to create a SAS dataset

Version 8 ODS (Output Delivery System)

Contents. Overview How SAS processes programs Compilation phase Execution phase Debugging a DATA step Testing your programs

Simplifying Your %DO Loop with CALL EXECUTE Arthur Li, City of Hope National Medical Center, Duarte, CA

8. Control statements

SAS Data Libraries. Definition CHAPTER 26

A Tutorial on the SAS Macro Language

Jeff Phillips, ARC Professional Services Group Veronica Walgamotte, ARC Professional Services Group Derek Drummond, ARC Professional Services Group

Tales from the Help Desk 5: Yet More Solutions for Common SAS Mistakes Bruce Gilsen, Federal Reserve Board

From Carpenter's Complete Guide to the SAS Macro Language, Third Edition. Full book available for purchase here.

ECLT 5810 SAS Programming - Introduction

Cpt S 122 Data Structures. Introduction to C++ Part II

INTRODUCTION TO SAS HOW SAS WORKS READING RAW DATA INTO SAS

Reading and Writing Data from Microsoft ExcellWord Using DDE Prepared by Destiny Corporation

SAS TM Macro Basics and Fundamentals Timothy J Harrington, Trilogy Consulting Corporation, Waukegan, IL

GET A GRIP ON MACROS IN JUST 50 MINUTES! Arthur Li, City of Hope Comprehensive Cancer Center, Duarte, CA

Anticipating User Issues with Macros

Lecture 1 Getting Started with SAS

SAS CURRICULUM. BASE SAS Introduction

Developing Varargs Macros For Integrated Clinical Study Analysis and Reporting. Lei Zhang Merck & Co. Inc. George Li Amgen Inc.

Macro Basics. Introduction. Defining and Using Macro Variables. Defining and Using Macros. Macro Parameters. Part 1. Chapter 1. Chapter 2.

A Time Saver for All: A SAS Toolbox Philip Jou, Baylor University, Waco, TX

Macro. simple idea of textual substitution useful when you need a group of instructions or directives frequently.

Arthur L. Carpenter California Occidental Consultants, Oceanside, California

Logging the Log Magic: Pulling the Rabbit out of the Hat

SAS Macro Dynamics: from Simple Basics to Powerful Invocations Rick Andrews, Office of Research, Development, and Information, Baltimore, MD

Customizing Your SAS Session

&&&, ;;, and Other Hieroglyphics Advanced Macro Topics Chris Yindra, C. Y. Training Associates

Chapter 7 File Access. Chapter Table of Contents

SAS PROGRAMMING AND APPLICATIONS (STAT 5110/6110): FALL 2015 Module 2

The Three I s of SAS Log Messages, IMPORTANT, INTERESTING, and IRRELEVANT William E Benjamin Jr, Owl Computer Consultancy, LLC, Phoenix AZ.

Journey to the center of the earth Deep understanding of SAS language processing mechanism Di Chen, SAS Beijing R&D, Beijing, China

The DATA Statement: Efficiency Techniques

QUEST Procedure Reference

Basic SQL Processing Prepared by Destiny Corporation

Contents of SAS Programming Techniques

USING SAS SOFTWARE TO COMPARE STRINGS OF VOLSERS IN A JCL JOB AND A TSO CLIST

Tired of CALL EXECUTE? Try DOSUBL

Lesson 1: Writing Your First JavaScript

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Macros are a block of code that can be executed/called on demand

PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILERS

Using Macro Functions

Chapter 2, Part I Introduction to C Programming

Your Own SAS Macros Are as Powerful as You Are Ingenious

Typescript on LLVM Language Reference Manual

What Is New in CSI-Data-Miner 6.0A and B?

m4 Macro Processor Overview (taken from the Internet)

Paper CC16. William E Benjamin Jr, Owl Computer Consultancy LLC, Phoenix, AZ

Hands-On Workshops. Creating Java Based Applications

Functions vs. Macros: A Comparison and Summary

<:ards,. The SAS" Macro: An Aid to the User 3' pfbl:me~~&j1tbc(lpt; 2435 procopt; RESOLVED RESOLVED

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

CROSSREF Manual. Tools and Utilities Library

My SAS Grid Scheduler

A LISP Interpreter in ML

Formulas and Functions

Transcription:

Basic Macro Processing Prepared by Destiny Corporation Macro variables In this module we discuss the first of the two special characters - the ampersand (&). When the SAS Supervisor sees an ampersand followed by a non-blank character, the macro facility is triggered. In turn, the macro facility, determines the value for the macro variable and passes the value back on to the input stack. If the macro facility fails to find the current value for a macro variable, the following message appears on the SAS Log: Warning: Apparent symbolic reference is not resolved. In version 5 systems this message is accompanied by the number 1301: Warning 1301: Apparent symbolic reference is not resolved. Strings enclosed within single blip quotes (') are always assumed to be one continuous string. Therefore, macro variable references within single quotes will NOT resolve. Tokens enclosed within double blip quotes (") are treated separately and thus macro variable references WILL resolve. In release 5.18 and below, the facility needs to be enabled by: OPTION DQUOTE; In version 6 the system works as though DQUOTE is always enabled. Predict the results of the following statements. Assume you are working on a version 6 system. There are certain variations in the variables available in different versions of the systems as shown below. Note that these are the automatic macro variables available with the base product only. Macro variables and their current values are stored in internal work areas called Symbol Tables. When the macro processor is trying to resolve a macro variable reference it will scan its symbol tables for a macro variable of that name and either retrieve its value and place that value upon the input stack, or the message Warning: Apparent Symbolic reference&macro-variable not resolved. will be issued. When the SAS system is invoked (and assuming system options enable the macro facility) the GLOBAL SYMBOL TABLE is built. This holds most of the automatic macro variables. Later we shall see other symbol tables created and deleted dynamically, how we can force variables into different tables and how the tables have a prescribed search order. Creating macro variables Within the macro facility and Data step language there are no fewer than 9 ways of creating a macro variable. We shall see all 9 methods throughout this course. Let us begin with the simplest method, the %LET statement. The presence of a % followed by a non-blank character triggers the macro facility. A %LET tells the macro facility that a macro variable is to be defined. %LET can appear anywhere within a SAS program to define one macro variable at a time. The form of the %LET statement is: %LET macrovariable = value; value is optional: %LET price=; The macro variable price is created but takes a null value. trailing and leading blanks are ignored: %LET cost= very cheap ; creates a macro variable called cost with the value of very cheap. Note the embedded blank is included but no blanks before very or after cheap are included. title Macro facility involves % and & ; title2 Macro facility came as a result of much R&D ; title3 "Macro facility came as a result of much R&D"; title4 "Report prepared on &sysdate"; title5 Report prepared on &sysday ; Automatic Macro Variables When SAS is invoked, a set of Automatic macro variables is created; some of these are read-only, others are read-write. We have encountered two of these so far -&SYSDATE and &SYSDAY. excepting the case above, all characters are included as part of the macro variable including any quotes used. %LET cost=' "very cheap" '; creates a macro variable called cost with the value ' "very cheap" ' including all quotes and spaces. Note that you cannot do %LET cost=' "very cheap" ; This will give unbalanced quotation mark errors. Copyright 1999 Desitny Corporation

inclusion of special characters in a macro variable value (except & or %) or leading or trailing blanks can be achieved by use of the %STR function: %LET code=proc print; %LET code2=%str(&code;); code1 takes the value of proc print code2 takes the value of proc print; to include & or % as part of the string use %NRSTR: %LET code=proc print; %put &stationa; %let stationb=%str(harrow&wealdstone); %put &stationb; %let stationc="&station7"; %put &stationc; These %LET and %PUT statements write the following Log: LOG NOTE: The PROCEDURE PRINTTO used 0.11 seconds. %LET code2=%nrstr(&code;); code1 takes the value of proc print code2 takes the value of &code; to inspect the variable's value simply use the %PUT statement to write the value of the Macro variable out to the log. Remember to reference it with an ampersand: %PUT &code; Writes the value of the macro variable code to the SAS Log. %let station1=paddington; %put &station1; %let station2=clapham Junction; %put &station2; %let prefix1=st; %let name1=pancras; %let station3=&prefix1 &name1; %let suffix1=street; %let name2=liverpool; %let name3=cannon; %let station4=%str( Victoria ); %put &station4; %let station5=&name2 &suffix1; %put &station5; %let station6= %put &station6; &name3 &suffix1; %let station7='tottenham Court Road'; %put &station7; %let station8=' Tottenham Court Road;Oxford Circus '; %put &station8; %let station9=%nrstr(highbury&islington); %put &station9; %let stationa=%str(chalfont&latimer); MPRINT(PROGRAM): DM 'clear log; clear out'; SYMBOLGEN: Macro variable N resolves to m234 SYMBOLGEN: Macro variable STATION1 resolves to Paddington Paddington SYMBOLGEN: Macro variable STATION2 resolves to Clapham Junction Clapham Junction SYMBOLGEN: Macro variable PREFIX1 resolves to St SYMBOLGEN: Macro variable NAME1 resolves to Pancras SYMBOLGEN: Macro variable STATION4 resolves to Victoria SYMBOLGEN: Some characters in the above value which Victoria SYMBOLGEN: Macro variable NAME2 resolves to Liverpool SYMBOLGEN: Macro variable SUFFIX1 resolves to Street SYMBOLGEN: Macro variable STATION5 resolves to Liverpool Street Liverpool Street SYMBOLGEN: Macro variable NAME3 resolves to Cannon SYMBOLGEN: Macro variable SUFFIX1 resolves to Street SYMBOLGEN: Macro variable STATION6 resolves to Cannon Street Cannon Street SYMBOLGEN: Macro variable STATION7 resolves to 'Tottenham Court Road' 'Tottenham Court Road' SYMBOLGEN: Macro variable STATION8 resolves to ' Tottenham Court Road;Oxford Circus ' ' Tottenham Court Road;Oxford Circus ' SYMBOLGEN: Macro variable STATION9 resolves to Highbury&Islington SYMBOLGEN: Some characters in the above value which Highbury&Islington WARNING: Apparent symbolic reference LATIMER not resolved. SYMBOLGEN: Macro variable STATIONA resolves to Chalfont&Latimer Copyright 1999 Destiny Corporation

SYMBOLGEN: Some characters in the above value which WARNING: Apparent symbolic reference LATIMER not resolved. Chalfont&Latimer ERROR: Symbolic variable name WEALDSTON must be 8 or fewer characters long. SYMBOLGEN: Macro variable STATIONB resolves to Harrow&Wealdstone SYMBOLGEN: Some characters in the above value which ERROR: Symbolic variable name WEALDSTON must be 8 or fewer characters long. Harrow&Wealdstone SYMBOLGEN: Macro variable STATION7 resolves to 'Tottenham Court Road' SYMBOLGEN: Macro variable STATIONC resolves to "'Tottenham Court Road'" "'Tottenham Court Road'" MPRINT(PROGRAM): PROC PRINTTO; MPRINT(PROGRAM): RUN; Notes on the log: %LET does not allow leading or trailing blanks - for them use quotes or the %STR function. Quotes remain part of the macro variable value. Note that blanks can be included and other special characters too - see Station8. Macro variable references can themselves be used within %LET statements. Macro variable names conform to usual SAS naming conventions. Note that although WEALDSTONE is 10 characters long, the Log reports WEALDSTON - 9 Characters. Once the limit of 8 characters is exceeded SAS reports the error. %STR( ) hides the meaning of blanks and special characters, but not & and %. A macro variable reference will resolve within the function. %NRSTR( ) hides the meaning of the % and& as well as blanks and other special characters. A macro variable reference within the argument to the function will NOT resolve. We have seen that the Global Symbol Table is built at SAS invocation time. All the %LETs in the example above will also be written to this table, and after they have executed the table will contain the following: Definition of a Macro As the module title implies, a macro is simply 'a bundle of code'. In its simplest form, the regular job you submit to backup your data sets or produce your graphics can all be bundled up into a macro and then 'invoked' using one word - the name of the macro. This is known as making a macro 'call'. But as you would expect, the macro facility can do far more than this. For example, we shall see how to pass values to the macro, and, in Module 5, how to take decisions within the macro. All this simply leads to the inclusion of text (normally ordinary SAS code - DATA and PROC steps) on to the top of the input stack, to be submitted to SAS in the normal way. Example Consider a regular job to age a series of time-related data sets; there are four data sets in the group. A new data set forms the first, newest member, the former first data set becomes the second and so on: data mylib.new;...... data step statements...... new is renamed first first is renamed second second is renamed third third is renamed fourth fourth is deleted How can we bundle this code up into a macro? Macro definition A macro must be defined first before it can be called. Macro definitions start with the %MACRO statement which defines the name of the macro...... and the definition is deemed to continue until the %MEND statement. Including the macro name is optional (but if it is used must correspond with the name of the macro): %macro macroname;. macro programming statements;. %mend macroname; The above example thus becomes: %macro age; /*definition of macro called age*/ datasets lib=mylib; %mend age; /*completion of macro definition*/ proc N.B. The %MEND is critical. The macro processor takes control when a %MACRO statement is seen. Should the %MEND be missing, all the input stream is regarded as being part of the open macro definition. There are occasions when all the submitted code is seen to be written to the log and nothing else - the code appears to be disappearing into a black hole! Upon such occasions, check for the absence of a %MEND statement. Copyright 1999 Desitny Corporation

What can a macro contain? Data and Proc step code Macro programming statements and functions We shall see these in Module M5. Some macro programming statements must be within the bounds of a macro definition, others are totally global. Macro variable references i.e. things starting with the & Other macro calls and definitions i.e. things starting with the % In the example we have just seen, the name of the data sets are fixed. We shall see how to make these variable shortly. What can a macro be called? Any valid SAS name (CMS users are limited to a maximum of 7 characters ) Anything other than one of the following reserved words: Reserved words in the macro facility (Release 6.06 and higher): ABEND GOTO QUOTE ABORT IF QUPCASE ACT INC RESOLVE ACTIVATE INCLUDE RETURN BQUOTE INDEX RUN BY INFILE SAVE CLEAR INPUT SCAN CLOSE KEYDEF STOP CMS LENGTH STR COMANDR LET SUBSTR COPY LIST SUPERQ DEACT LISTM SYSEXEC DEL LOCAL SYSGET DELETE MACRO SYSRPUT DISPLAY MEND THEN DMIDSPLY METASYM TO DMISPLIT NRBQUOTE TSO DO NRQUOTE UNQUOTE EDIT NRSTR UNSTR ELSE ON UNTIL END OPEN UPCASE EVAL PAUSE WHILE FILE PUT WINDOW GLOB QSCAN GO QSUBSTR An attempt to call a macro by one of the above reserved names will result in a warning message; the macro will neither be compiled or available for use. The compiled macro A compiled macro is an entry in a utility catalog in the WORK library the system does not support the renaming or copying of entries of member type of macro The once-defined macro is stored in the WORK data library in compiled form. In versions prior to 6.03 it was stored as a special type of data set; in version 6.03 and above, it is stored in the WORK.SASMACR catalog with an entry type of MACRO. As it is held in 'compiled' form, it is, of course, not browsable or editable. The macro could also be part of an autocall library. This topic will be discussed at length in a later module. The Macro Call Once a macro has been defined it can be called anywhere in a SAS job. is simply the name of the macro preceded by the % sign: %macro age; /*definition of macro called age*/ %mend age; /*completion of macro definition*/ data mylib.new; set...; if...; %age /*the macro call*/ Notice that the macro call, %age, does not include a semi-colon. There is no need here as a semi-colon has been generated by the macro call; the code within the definition is complete, so no extra semi-colon is required. The macro call sees the execution phase of the macro, whereupon the macro processor executes the macro in sequential form, placing the resulting open code (i.e. simple DATA and PROC steps) upon the input stack. Passing Parameters In the %age example the data set names fixed. How could a macro be written such that the procedure is invoked with any names for the library and data sets involved? I.e. to generate: at the first invocation and to generate proc datasets lib=newlib; age next ds_0 ds_1 ds_2; at the next? The way to do this is to pass parameters to the macro call. To use this method, the macro must first be defined as requiring parameters in the call. There are two ways of doing this: Positional Parameters Copyright 1999 Destiny Corporation

data new; x=5; data first ; x=1; data second; x=2; data third ; x=3; data fourth; x=4; %macro age(library,newds,ds1,ds2,ds3,ds4); proc datasets lib=&library; age &newds &ds1 &ds2 &ds3 &ds4; quit; %mend; %age(work,new,first,second,third,fourth) Here the macro age has been defined with six positional parameters to take the variation in library and data sets - in order. The macro is invoked by: %age(sasdata,latest,prod1,prod2,prod3,prod4) to generate: proc datasets lib=sasdata; age latest prod1 prod2 prod3 prod4; What would the call %age(prod1,prod2,prod3,prod4,sasdata,latest) generate? Keyword Parameters This method does exactly the same job as defining a macro with positional parameters, except: it gets over the requirement to define and pass parameters in the same order it allows default values to be attached to the parameter data new; x=5; data first ; x=1; data second; x=2; data third ; x=3; data fourth; x=4; %macro age(library=work,newds=new,ds1=,ds2=,ds3=,ds4=); proc datasets lib=&library; age &newds &ds1 &ds2 &ds3 &ds4; quit; %mend; %age(ds1=first,ds2=second,ds3=third,ds4=fourth) %age(ds1=first,ds2=second,ds3=third,ds4=fourth) generates... age work1 first second third fourth; the definition of the macro providing default values for &library and &newds. %age(ds2=april,ds4=june,ds1=march,ds3=may,library=ye arlib) generates proc datasets lib=yearlib; age work1 march april may june; Where the macro is defined with parameters the parentheses MUST be used. For example, where all the parameters are given default values, the minimum invocation is: %age() Null values With positional parameters, null values can be passed by using a comma as a 'placeholder': %macro rr(datads,setds,condval); data &datads; set &setds; if category="&condval"; %mend rr; %rr(work9,saved.epidemic,e) %rr(,saved.epidemic,e) %rr(,work3,f) will generate: data; set work3; if key="f"; and SAS will choose the name of the temporary output data set. %rr(,,m) will generate: data; set; if key="m"; Copyright 1999 Desitny Corporation

and SAS will choose the name of the temporary output data set and use the last updated data set as input. With keyword parameters, the parameter is simply omitted. Combination of Positional and Keyword parameters If the methods of positional and keyword parameters are mixed, the positional parameters must come first. %macro tt(proc,dataset=_last_); proc &proc data=&dataset; %mend tt;... %tt(print,dataset=first)...generates proc print data=first; %mend age; In the above example, a different number of parameters can be supplied as long as there is at least one. %age(mylib,new,gdg_0,gdg_1,gdg_2) gives a value to &syspbuff of mylib,new,gdg_0,gdg_1,gdg_2 and &posparm the value mylib. Prepared by: Destiny Corporation 100 Great Meadow Rd Suite 601 Wethersfield, CT 06109-2355 Phone: (860) 721-1684 1-800-7TRAINING Fax: (860) 721-9784 Email: info@destinycorp.com Web: www.destinycorp.com Copyright 1999 Variable Numbers of Parameters Sometimes you may want to write a macro to contain variable numbers of parameters. For example, the %age macro in its forms defined so far can only age 5 data sets; what if we wanted to write a utility macro so we could age any number of data sets. A way around this is to use the PARMBUFF option. Define the macro in the normal way except for the /PARMBUFF option. %macro age/parmbuff; macro programming statements %mend age; Here, all supplied parameters, including any special characters used are assigned to the automatic local macro variable SYSPBUFF which is then manipulated in the macro by macro programming statements. %age(library=mylib,new,gdg_0,gdg_1,gdg_2) gives a value to &syspbuff of library=mylib,new,gdg_0,gdg_1,gdg_2 Parameters may also be included in the definition %macro age(posparm)/parmbuff; macro programming statements Copyright 1999 Destiny Corporation