1、MacroOctober07Topic SAS Macro Language1. Overview of SAS Macro Language2. Macro Variables3. Introduction to Automatic Macro Variables4. Macro Program5. Interfaces to the Macro Facility6. Macro Statements 7. Macro Functions8. System Options 9. Storing Macro Programs10. A Stepwise Methods for Writing
2、Macro Programs1. Overview The macro facility is a tool for extending and customizing the SAS System and for reducing the amount of text you must enter to do common tasks. It allows you to assign a name to character strings or groups of SAS programming statements. The SAS macro facility is a componen
3、t of base SAS. The baseSASproduct is integral to the SAS system. The macro facility has it own language distinct from the SAS language, but the language and conventions of the macro facility are similar to the style and syntax of the SAS language. The SAS macro facility has two components:A. The mac
4、ro processor is the portion of the SAS system that does the work.B. The macro language is the syntax that you use to communicate with the macro processor. The components of the Macro Language are Macro Variables, Macro Statements, Macro Functions, and Macro expressions & Constant Text.1.1 Introducti
5、on of Macro ProcessingThis topic describes a typical pattern that the SAS System follows to process a program. These concepts are helpful in understanding how the macro processor works with other parts of the SAS System. However, they are not required for most macro programming. They are provided so
6、 that you can understand what is going on behind the scenes. Note:The concepts here present a logical representation, not a detailed physical representation, of how SAS software works.When you submit a program, it goes to an area of memory called the input stack. This is true for all program and com
7、mand sources: the Display Manager, the SCL SUBMIT block, the SCL COMPILE command, or from batch or noninteractive sessions. The input stack shown contains a simple SAS program that displays sales data. Once a program reaches the input stack, SAS transforms the stream of characters into individual to
8、kens. These tokens are transferred to different parts of the SAS System for processing, such as the DATA step compiler, the macro processor, and the SAS procedures. Knowing how SAS recognizes tokens and how they are transferred to different parts of the SAS System will help you understand how the va
9、rious parts of the SAS System and the macro processor work together and how to control the timing of macro execution in your programs. The following sections show you how a simple program is tokenized and processed.TokenizationBetween the input stack and the compiler, SAS programs are tokenized into
10、 smaller pieces. The process that SAS uses to extract words and symbols from the input stack is called tokenization. A component of SAS known as the word scanner divides program text into fundamental units called tokens. The word scanner starts at the first character in the input stack and examines
11、each character in turn. In doing so, the word scanner assembles the characters into tokens. In this example, when the word scanner pulls the first token from the input stack, it recognizes the token as the beginning of a DATA step. The word scanner triggers the DATA step compiler, which begins to re
12、quest more tokens. Tokens are passed on demand to the compiler. The compiler requests tokens until it receives a semicolon. The compiler performs a syntax check on the statement. The word scanner recognizes four types of tokens: A literal token is a string of characters that are treated as a unit. T
13、he string is enclosed in either single or double quotation marks. Examples: Any textAny text A number token is a string of numerals that can include a period or E-notation (real numbers). Date constants, time constants, datetime constants, and hexadecimal constants are also number tokens. Examples:
14、2310901jan2002d5e842.7 A name token is a string of characters that begins with a letter or underscore and that continues with underscores, letters, or digits. A period can sometimes be part of a name. Examples: infile_n_item3univariatedollar10.2 A special token is any character or group of character
15、s that has a reserved meaning to the compiler. Examples: */+-*;$().&% A token ends when the word scanner detects the beginning of another token a blank after a token. The maximum length of any token is 32767 characters.Examples var x1-x10 z; This example contains six tokens: var x1 - x10 z ; title R
16、eport for May; This example contains three tokens: title Report for May ; 1.2 What are the advantages of the SAS macro facility?It provides tools that Avoid repetitious SAS code Pass information between SAS steps Dynamically create code at execution time Conditionally execute DATA or PROC steps Crea
17、te generalizable and flexible codeSAS macro facility can accomplish repetitive tasks quickly and efficiently. A macro program can be reused many times. Parameters passed to the macro program customize the results without having to change the code within the macro program. SAS macro also provides a m
18、ore modular structure to your programs.1.2.1 There are two delimiters to trigger macro processor activity& name refers to a macro variable, is called a macro variable reference. It triggers an attempt at symbolic substitution, which is the resolution of a macro variable.% sign can trigger macro invo
19、cation, the attempt to invoke the defined macro and to execute the macro, sometimes to trigger macro function ( %evl, % upcase), programming statements (%let %if %then %do %end).1.3 Macro Statements-begin with a % and a macro keyword and end with semicolon (;).-assign values, substitute values, and
20、change macro variables.-can branch or generate SAS statements conditionally.-Macro statements are given to the macro processor BEFORE the compiler.1.3.1 Some are valid anywhere in SAS code. Such as %let, %put, %display, and %include.1.3.2 Others are valid only inside a macro definition. Such as %if
21、%then; %else, %do %end; %do %while %end; %local.2. Macro VariablesThe two mail tools of the SAS macro facility are SAS macro variables and SAS macro programsMacro variables, which are also known as symbolic variables, are not data set variables, and used to replace text strings in SAS code.2.1 Basic
22、 Rules to Name Macro Variables A name can be from one to eight characters in length. A name must begin with a letter or underscore (_). Only letters, numbers, and underscores can follow the first character. The content of macro variable can be up to 32K. No macro variable can have the same name as a
23、 SAS-supplied macro or macro function.There are many features of macro variables.1. A macro variable can be referenced anywhere ina SAS program other than in data lines.2. A macro variable can be used in open code as well as in macro programs.3. A macro variable can be created by the SAS system and
24、by your programs.There are two types of macro variables: automatic macro: sasday, sasdate, sastime user-defined 4. A macro variable can be stored in either the global symbol table or in a local symbol table.5. Macro variable values are text values. All values assigned to macro variable are considere
25、d text values. This includes numbers. The case of the character value assigned to a macro variable is preserved. That is, a value in lowercase remains lowercase, uppercase remains uppercase, and mixed case remains mixed case.6. The name assigned to a macro variable must be a valid SAS name.7. They a
26、re not data set variable and they have a different purpose from data set./*example: user-defined macro variable*/;data school_one; input stu_id score1 score2 age sex $ ; datalines;123456789 92 90 18 F 231568765 90 89 17 F423055789 86 85 19 M 582774165 90 93 17 M;%let ss=school_one;%let s_sum=score1
27、;%put data set is &ss;%put The value for macro variable s_sum is &s_sum;proc print data=&ss;var &s_sum;title Data for the &SS;run;/*example: user-defined macro variable content*/;%let age4=%str(if age 20 then group = 20 ; else if age 35 then group = 20-34; else if age 45 then group = 35-44; else gro
28、up = 45+ ;);%let age2=%str( if age 35 then group = 35;else group = 35+;);data test;input age ;&age4;datalines;19 50 10 34 44 15 30;run;2.2 Defining and Using Macro VariablesThe simplest way to define a macro variable is to use the %LET statement to assign the macro variable a name, and a value. The
29、name of macro variables is almost always preceded by an ampersand (&) in SAS code. Here is a simple example:%let city = New Orleans;title “ Data for &city “ title “ Data for New Orleans “;Note: the macro processor resolves macro variable references within double quotation marks but NOT within single
30、 quotation marks.A %LET statement in open code (outside a macro definition) creates a macro variable that is available for use anywhere in your SAS code during the SAS session in which the variable was created.%LET StatementVariable NameVariable ValueLength%let name= Ed Norton ;nameEd Norton9%let na
31、me2= Ed Norton ;name2 Ed Norton 13%let title=Joans Report;titleJoans Report15%let start=;start0%let total=0;total01%let sum=4+3;Sum4+33%let total=&total+∑total0+4+35%let x=varlist;Xvarlist7%let &x=name age height;varlistname age height15Macro variables are not subject to the same length limits as SAS data set variables.The common system options for displaying macro variables are as follows:_all_ lists all macro variables in all reference environments including both user and system defined macro variables to the log.