11 chapter 2: framework for developing macro applications 2.1 applying best practices 2.2 debugging...

Post on 17-Dec-2015

231 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

11

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

22

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

3

Objectives Perform application development in stages. Implement parameter validation. Store re-usable code as macro programs. Create local macro variables. Add comments to macro programs.

3

4

Developing Best PracticesIn order to improve macro application development, the Orion Star programmers implemented these guidelines for new programs and applications:

1. Develop the application in stages.

2. Prevent program failures associated with user-supplied values by validating parameters.

3. Create user-defined macro functions or routines for repetitive tasks.

4. Create local macro variables when possible.

5. Document all programs to help with maintenance.

4

5

Guideline 1: Develop in StagesTo isolate SAS syntax/logic from macro syntax/logic during development, implement your application in stages.

Stage 1: Write and debug the desired code without macro techniques. Use hardcoded program elements. Use a fixed set of data.

5

proc print data=orion.continent; title "ORION.CONTINENT Data Set";run;

continued...

6

Guideline 1: Develop in StagesStage 2: Generalize the application. Activate the SYMBOLGEN system option for

debugging macro variable resolution. Replace hardcoded elements with macro variable

references. Use %LET statements to try different values.

6

options symbolgen;%let dsn=orion.continent;proc print data=&dsn; title "%upcase(&dsn) Data Set";run;

continued...

7

Guideline 1: Develop in StagesStage 3: Create a macro definition. Convert %LET statements to macro parameters. Activate the MPRINT system option to view the

generated SAS code. Call the macro with different parameter values.

7

%macro printone(dsn); proc print data=&dsn; title "%upcase(&dsn) Data Set"; run;%mend printone;

options mprint;%printone(orion.continent)

continued...

8

Guideline 1: Develop in StagesStage 4: Add macro-level programming. Perform conditional logic with %IF statements. Perform iterative logic with %DO statements. Activate the MLOGIC system option to verify the

macro programming flow and logic.

8

%macro printone(dsn); %if &dsn ne %then %do; proc print data=&dsn; title "%upcase(&dsn) Data Set"; run; %end;%mend printone;

options mlogic;%printone(orion.continent)

9

Guideline 2: Validate ParametersThe Orion Star programmers found that user-supplied parameters can cause difficulties for macro applications. They decided that macro applications should test parameters for the following conditions: null values invalid values cross-validation of parameters

9

10

Guideline 2: Validate ParametersTo validate parameters, perform these steps:

1.Establish rules for valid values with the following criteria, for example:

a. Are null values valid?

b. What are valid values?

2.Validate parameter values against valid values.

3.Generate an error or warning message when invalid values are encountered. Possibly terminate the macro.

10

1111

12

2.01 QuizBased on the following macro definition, what parameter values could cause this program to fail?

12

%macro printdsn(path, dsn, obs); libname orion "&path"; proc print data=orion.&dsn (obs=&obs); run;%mend printdsn;

m202a01

13

2.01 Quiz – Correct AnswerBased on the following macro definition, what parameter values could cause this program to fail?

13

Based on the following macro definition, what parameter values could cause this program to fail? Null values for any of three parameters could cause

a problem with the macro’s execution. An invalid path could cause the macro to fail. Special characters, such as & and % found in the path

value, could cause problems with the macro call. An invalid data set name or nonexisting data set could

cause the macro to fail. A nonnumeric value for OBS could cause the macro

to fail.

14

Guideline 3: Create Reusable MacrosSome Orion Star macro programs became lengthy and difficult to maintain. Instead of writing one massive program, the programmers decided to develop small modules or macros and then put them together. The advantages of writing a macro definition in smaller pieces include the following: testing of each piece separately maintaining each piece separately creating reusable modules of code

14

15

Guideline 3: Create Reusable MacrosOther advantages of building a library of reusable macros include the following: simplifying code hiding complex code sharing and reusing code reducing maintenance

15

1616

17

2.02 QuizOpen the program m202a02.

Which sections can be placed in separate macros and considered reusable?

17

18

2.02 Quiz – Correct AnswerOpen the program m202a02.

Which sections can be placed in separate macros and considered reusable? the %PUT statements for message generation the routine to convert macro variable to uppercase the routine that checks the number of

observations

18

19

Guideline 4: Create Local Macro VariablesWhenever possible, Orion Star applications should create local macro variables. Local macro variables exist only as long as a macro executes. Using local macro variables prevents the following: inadvertently altering a global macro variable's value needing to delete macro variables after a macro

finishes executing

19

20

Guideline 5: Comment Macro ApplicationsComments were somewhat lacking in the past. Orion Star decided that every macro should start with a comment block that describes its functionality, parameters, and requirements.

Comments in a macro program can be defined using these techniques: %* macro comment statements; /* block comments */ * SAS comment statements;

Comments in the form of /* comment */ are the safest comments to use inside a macro definition.

20

21

Guideline 5: Comment Macro ApplicationsPartial SAS Program

21

%macro archive(dsn);

/*-----------------------------------------------------*/ /* ARCHIVE - Archive data set, appending current date */ /* to build a new (unique by day) name for the copy. */ /*-----------------------------------------------------*/ /* Parameter DSN: Master table to be archived */ /*-----------------------------------------------------*/ /* Requires these other macros: */ /* %VALIDDSN - validates a SAS data set name */ /*-----------------------------------------------------*/

%* %put Activating the MPRINT and MLOGIC options.;

*options mprint mlogic;

2222

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

23

Objectives Use macro debugging options during macro

development.

23

24

Debugging and Troubleshooting MacrosThe Orion Star programmers encountered different challenges during macro development versus macro use.

During development they encountered the following problems: macro logic and code generation errors the open code recursion error the "Black Hole" macro problem

24

25

Development Debugging Options (Review)These two solutions enable tracing macro variable resolution: the SYMBOLGEN option to display the results of

resolving macro variable references the %PUT statement to write a variable's value to the

log

These three solutions aid in debugging macro definitions: the MLOGIC option to display macro execution

messages the MPRINT option to display SAS statements

generated by macro execution the %PUT statement to check the evaluation of a

condition

25

26

Solving Open Code Recursion Problems Open code recursion occurs when your code mistakenly causes a macro statement to call another macro statement. The most common reason is a missing semicolon.

SAS Log

26

115 %let newvar=new value116 %put NEWVAR has the value &newvar;ERROR: Open code statement recursion detected.

A missing semicolon in the %LET statement caused the open code recursion.

27

Solving Open Code Recursion Problems To recover from an open code recursion error, first submit a single semicolon. If that does not work, submit the following code:

Submit this string until this message appears in the SAS log:

27

*'; *"; *); */; %mend; run;

ERROR: No matching %MACRO statement for this %MEND statement.

28

Solving the “Black Hole” Macro Problem A “Black Hole” macro problem occurs when the SAS windowing environment stops responding after you submit a macro definition. You type and submit code, but nothing happens.

Generally this occurs when the macro processor does not recognize the %MEND statement and all text becomes part of the macro definition. This can happen as a result of one of these problems: omitting a %MEND statement omitting a semicolon in the statement preceding the

%MEND statement unmatched quotation marks or unclosed parentheses an unclosed comment

28

29

Solving the “Black Hole” Macro Problem

29

120 %macro printone(dsn);121 %if &dsn ne %then %do;122 proc print data=&dsn;123 title "%upcase(&dsn) Data Set";124 run;125 %end126 %mend printone;NOTE: Extraneous information on %END statement ignored.127 %printone(orion.continent)128 %put This should print in the log.;129 %put So should this.;

The missing semicolon in the %END statement causes the windowing environment to stop responding.

The PRINTONE macro and the %PUT statements do not execute.

30

Solving the “Black Hole” Macro Problem To exit the macro “Black Hole,” submit the following code:

Submit this string until the following message appears in the SAS log:

30

*'; *"; *); */; %mend; run;

ERROR: No matching %MACRO statement for this %MEND statement.

3131

32

2.03 Quiz1. Open and submit the program m202a03.

2. Look at the log to determine the reason that the macro does not execute.

3. Correct the problem and resubmit the program.

4. If the macro still fails to execute, type and submit the following statement:

5. When the following message appears in the log, submit the macro definition and ensure that it executes properly.

32

*'; *"; *); */; %mend; run;

ERROR: No matching %MACRO statement for this %MEND statement.

3333

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

34

Objectives Write custom messages to the log. Write custom messages using the DATA step. Use the %WINDOW and %DISPLAY statements.

34

35

Generating Custom Messages

35

The Orion Star users requested feedback via custom messages.

To facilitate this request, the programmers will use one of these three techniques: the %PUT statement to display messages in the

Log window the DATA step to write to the current output location %WINDOW and %DISPLAY statements to create

a custom message window

After the messages are issued, the macro’s execution can be terminated if the error is severe.

36

Terminating Macro Execution To terminate macro execution, use the %RETURN statement.

General form of the %RETURN statement:

To terminate the currently executing macro, along with the current SAS job or SAS session, use the %ABORT statement with the ABEND option.

General form of the %ABORT statement:

36

%RETURN;%RETURN;

%ABORT ABEND;%ABORT ABEND;

37

Terminating Macro Execution The %RETURN and %ABORT statements usually appear as part of %IF-%THEN logic and generally eliminate the need for %ELSE statements.

37

%macro printone(dsn); %if &dsn eq %then %return; proc print data=&dsn; title "%upcase(&dsn) Data Set"; run;%mend printone;

The %RETURN statement eliminated the need for the PROC PRINT step to be contained within %ELSE logic.

38

Generating Custom Log MessagesThe Orion Star programmers will generate custom log messages using the %PUT statement.

To make the custom messages resemble standard ERROR, NOTE, and WARNING messages, start the message text with the corresponding keyword.

Partial SAS Log

38

ERROR: This is an error message.WARNING: This is a warning message.NOTE: This is a note.

%put ERROR: This is an error message.; %put WARNING: This is a warning message.; %put NOTE: This is a note.;

m202d01

39

Generating Custom Log Messages For messages that span several lines, it might be desirable to suppress the words ERROR, NOTE, and WARNING on subsequent lines.

Use a hyphen instead of a colon to suppress the keywords.

Partial SAS Log

39

%put ERROR: This is an error message.;%put ERROR- It spans several lines.;%put ERROR- Notice the indention.;

ERROR: This is an error message. It spans several lines. Notice the indention.

m202d01

40

Generating Custom Output Messages

40

a DATA _NULL_ statement to invoke the DATA step a FILE statement to direct the output PUT statements to write lines to the specified output

location a RUN statement to terminate the DATA step

A typical DATA step for writing text contains at least four

parts:

The DATA step is generally used to create data sets but can also be used to write custom text to the current output destination.

41

Generating Custom Output Messages

41

data _null_; file print; put #5 @20 "Welcome to SAS Macro Language 2"; run;

The PRINT option in the FILE statement sends the results to the current output location (Output window, LST file, or SASLIST location).

DATA Step Output

42

Generating Custom Output Messages

This demonstration illustrates using the DATA step to generate custom messages in the Output window.

42m202d02

43

Creating Custom Message Windows Use the %WINDOW statement to define the size, text, and attributes of the custom message window.

General form of the %WINDOW statement:

43

%WINDOW window-name <columns=n rows=n>

field-definition-1 <field-definition-n>;

%WINDOW window-name <columns=n rows=n>

field-definition-1 <field-definition-n>;

%window welcome columns=25 rows=10 #3 @10 'Welcome to SAS Macro Language 2.' #5 @10 'Press ENTER to close this window.';

44

Creating Custom Message Windows Use the %DISPLAY statement to display the window.

General form of the %DISPLAY statement:

44

%DISPLAY window-name;%DISPLAY window-name;

%display welcome;

45

Using %WINDOW and %DISPLAY to Generate Custom Message Windows

This demonstration illustrates using the %WINDOW and %DISPLAY statementsto create a custom message window.

45m202d03

46

Generating Custom Messages

46

%PUT DATA Step

%WINDOW %DISPLAY

Interactive SAS X X X

SAS Enterprise Guide X X

Noninteractive Programs X X X

Stored Processes X

SAS/IntrNet Applications X

With any application, also consider the user of the application when you determine the best method.

Although the different methods are not mutually exclusive,there are situations or applications where one is more appropriate.

47

Exercise

This exercise reinforces the concepts discussed previously.

47

4848

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

49

Objectives Avoid excessive macro processing. Use memory resources efficiently. Create autocall macros to minimize macro

compilation. Create stored compiled macros to avoid repeated

macro compilation.

49

50

Efficiency Considerations with Macro “The macro facility is a powerful tool for making your

SAS code development more efficient.”

“Usually, efficiency issues are discussed in terms of CPU cycles, elapsed time, I/O hits, memory usage, disk storage, and so on.”

“The area of efficiency most affected by the SAS macro facility is human efficiency – how much time is required to both develop and maintain a program.”

from SAS® Macro Language: Reference

50

51

Macro More EfficientThe Orion Star programmers realize that incorporating macro code into a SAS application does not necessarily make the application more or less efficient. Because most macros generate SAS code, they want to concentrate on making the resulting SAS code more efficient.

They plan to use macro techniques only when necessary. They will balance efficiency factors to reach a solution that is best for the application. Considerations include the following: how often you run the application machine resource savings versus maintainability

and ease of use

51

52

Avoiding Extra Macro Processing

1. Avoid nested macro definitions.

2. Minimize function calls, which are CPU-intensive, by assigning function results to macro variables.

3. Delete global macro variables.

4. Use the %RETURN statement to terminate macros when parameters fail validation and to eliminate the need for additional %ELSE logic.

5. Turn off macro debugging options in production jobs.

6. Store and reuse macros.

52

Methods to minimize the work performed by the macro processor include the following:

53

Example 1: Avoid Nested Macro DefinitionsWhen macro definitions are nested, the execution of the OUTER macro includes recompilation of the INNER macro.

53

%macro outer; proc catalog cat=work.sasmacr; contents; title "Macros Before Nested Macro"; run; %macro inner; %put The inner macro is executing.; %mend inner; contents; title "Macros After Nested Macro"; run; quit;%mend outer;%outer

m202d04

54

Example 1: Avoid Nested Macro DefinitionsPartial PROC CATALOG Output

54

Macros Before Nested Macro

Contents of Catalog WORK.SASMACR

# Name Type Create Date Modified Date ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ1 OUTER MACRO 23Jun08:18:18:12 23Jun08:18:18:12

Macros After Nested Macro

Contents of Catalog WORK.SASMACR

# Name Type Create Date Modified Dateƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ1 INNER MACRO 23Jun08:18:18:13 23Jun08:18:18:132 OUTER MACRO 23Jun08:18:18:12 23Jun08:18:18:12

55

Example 2: Assign Results to VariablesAssigning macro function results to a macro variable provides the following functionality: Repeated execution of the same macro function can

be avoided. Leading and trailing blanks are removed automatically

through the %LET statement. Intermediate results can be monitored using the

SYMBOLGEN system option during debugging.

55

56

Example 2: Assign Results to VariablesUse this program:

56 m202d05

Instead of this program:%macro country(name); proc print data = orion.country; where upcase(Country_Name)="%upcase(&name)"; title "Report for %upcase(&name)"; run;%mend country;

options symbolgen;%country(united states);

%macro country(name); %let name=%upcase(&name); proc print data=orion.country; where upcase(Country_Name)="&name"; title "Report for &name"; run;%mend country;

options symbolgen;%country(united states);

57

Example 3: Delete Macro VariablesBecause symbol tables are stored in memory, deleting macro variables when they are no longer needed can save memory resources. To delete global macro variables, use the %SYMDEL statement.

Partial SAS Log

57

%global VAR1 VAR2 VAR3 VAR4 VAR5 ;%put _global_;GLOBAL VAR1GLOBAL VAR2GLOBAL VAR3GLOBAL VAR4GLOBAL VAR5

%symdel VAR1 VAR2;%put _global_;GLOBAL VAR3GLOBAL VAR4GLOBAL VAR5

m202d06

58

Example 3: Delete Macro VariablesTo delete a series of macro variables, use the SYMDEL routine in the DATA step.

General form for the SYMDEL routine:

58

CALL SYMDEL(<macro-variable>); CALL SYMDEL(<macro-variable>);

where macro-variable can be any of the following: the name of a macro variable within quotation marks

but without an ampersand the name of a DATA step character variable, specified

with no quotation marks, which contains the name of a macro variable

a character expression that constructs a macro variable name

5959

60

2.04 QuizOpen the program m202a04. Add the following statement after the %GLOBAL statement and after the DATA _NULL_ step:

1.What was the result of the %PUT statement after the %GLOBAL statement?

2.What was the result of the %PUT statement after the DATA _NULL_ step?

60

%put _global_;

61

2.04 Quiz – Correct AnswerOpen the program m202a04. Add the following statement after the %GLOBAL statement and after the DATA _NULL_ step:

1.What was the result of the %PUT statement after the %GLOBAL statement?

61

%put _global_;

57 %global VAR1 VAR2 VAR3 VAR4 VAR5 ;5859 %put _global_;GLOBAL VAR1GLOBAL VAR2GLOBAL VAR3GLOBAL VAR4GLOBAL VAR5

continued...

62

2.04 Quiz – Correct Answer2. What was the result of the %PUT statement after the

DATA _NULL_ step?

62

data temp; set sashelp.vmacro; where scope='GLOBAL' and name like 'VAR%';run; NOTE: There were 5 observations read from the data set SASHELP.VMACRO. WHERE (scope='GLOBAL') and name like 'VAR%';NOTE: The data set WORK.TEMP has 5 observations and 4 variables data _null_; set temp; call symdel(name);run; NOTE: There were 5 observations read from the data set WORK.TEMP. %put _global_;

No macro variables are listed. All were deleted.

63

Example 4: Use the %RETURN Statement Because the %RETURN statement terminates normal execution, the %ELSE statement is not required.

63

%macro no_else(dsn); %if &dsn = %then %return; proc print data=&dsn; title "%upcase(&dsn) Data Set"; run;%mend no_else;

64

Example 5: Deactivate Debug Options in ProductionTurn off the SYMBOLGEN and MLOGIC system options in production jobs. Writing messages to the log expends resources. Custom error messages written to the log might be

more difficult to locate.

Keep the MPRINT system option synchronized with the SOURCE system option to request (or suppress) the display of executed SAS code in the SAS log.

64

65

Example 6: Store and Reuse MacrosSession-compiled macros are macros that are compiled and stored in a SAS catalog in the Work library and only exist during the current SAS session. Orion Star plans to save frequently used macros between sessions, using either the autocall macro facility or the stored compiled macro facility.

65

Autocall macro facility

stores the source code for SAS macros in a collection of external files or SAS catalogs called an autocall library. The macro is automatically compiled when the macro is called.

Stored compiled macro facility

stores compiled macros in a permanent SAS catalog.

66

Example 6: Store and Reuse MacrosThe Orion Star programmers plan to use the autocall facility in these circumstances: New macro programs are being developed. A group of users or an application shares macros. A macro definition is routinely modified. A macro is used in different operating environments.

66

67

Creating an Autocall MacroTo create an autocall macro, the name of the file must match the macro name. For the PRINTDSN macro to be an autocall macro, it is saved in a file named PRINTDSN.

Each autocall macro is stored as one of the following: a file with the extension .sas for directory-based

systems

a member of a partitioned data set (PDS) for z/OS

67

The UNIX operating system requires the filename to be in lowercase letters.

68

Accessing Autocall MacrosThe following steps enable you to access a macro defined in an autocall library:

68

1. Specify the SAS system option MAUTOSOURCE.

2. Use the SAS system option SASAUTOS= to identify the name of the autocall library or to associate a fileref of SASAUTOS with the autocall library.

3. Call any macro in the library during the SAS session.

69

Autocall Facility System OptionsThe MAUTOSOURCE system option controls whether the autocall facility is available.

General form of the MAUTOSOURCE system option:

The default option is MAUTOSOURCE.

69

OPTIONS MAUTOSOURCE | NOMAUTOSOURCE;OPTIONS MAUTOSOURCE | NOMAUTOSOURCE;

70

Autocall Facility System OptionsThe SASAUTOS= system option controls where the macro facility looks for autocall macros.

General form of the SASAUTOS= system option:

The values of library-1 through library-n are references to source libraries containing macro definitions.

The fileref SASAUTOS identifies the location for the autocall macros supplied by SAS.

70

OPTIONS SASAUTOS=(library-1,...,library-n, SASAUTOS);OPTIONS SASAUTOS=(library-1,...,library-n, SASAUTOS);

71

Accessing Autocall Macros

71

Does the macro exist in the

autocall library?

Include and submita macro definition tocompile the macro.

Execute thecompiled macro.

WARNING: Apparentinvocation of macro

not resolved.

No

Yes

Does the macro exist in the Work

library?

Execute thecompiled macro.

No

Yes

72

Accessing Autocall MacrosTwo problems might occur when you create and/or debug autocall macros. An incorrect path specification exists in the

SASAUTOS= option. The autocall macro is changed, but subsequent calls

to the macro do not reflect the changes.

72

73

Debugging Autocall MacrosWhat do you do if you cannot access your autocall macro?

The most common reason for this warning is an incorrect path specification in the SASAUTOS= option. By default, SAS does not search the autocall libraries for a member that was not found during an earlier search.

73

WARNING: Apparent invocation of macro not resolved.

Correcting the SASAUTOS= option does not result in SAS locating the autocall macro.

74

Debugging Autocall MacrosUse the MRECALL option to recover from errors caused by a call to a macro in an unavailable autocall library.

General form of the MRECALL option:

Set the MRECALL option and call the macro again after making the autocall library available.

74

OPTIONS NOMRECALL | MRECALL;OPTIONS NOMRECALL | MRECALL;

75

Debugging Autocall Macros

exit SAS delete the session-compiled macro use the %INCLUDE statement to recompile the new

modified autocall macro

75

%INCLUDE 'external-file' | fileref;%INCLUDE 'external-file' | fileref;

General form for the %INCLUDE statement:

After an autocall macro is compiled, SAS will not recompile the source code even if the macro definition changed. It is important to do one of the following:

7676

77

2.05 Quiz1. Open and submit the program m202a05 that calls

the autocall macro FREQ. Did the macro execute?

2. Uncomment the appropriate OPTION statement to modify the SASAUTOS= option and resubmit the program. Did the macro execute?

3. Add the MRECALL option and resubmit the program. Did the macro execute?

4. Open the program FREQ, uncomment the %PUT statements, and save the changed program.

5. Submit the following macro call:

Were the messages from the %PUT statements written to the log?

77 continued...

%freq(,Customer_Gender)

78

2.05 Quizz6. Does the MRECALL option force the FREQ macro to

be recompiled?

7. Submit the following %INCLUDE statement and macro call:

Were the messages from the %PUT statements written to the log?

78

%include 'freq.sas';%freq(,Customer_Gender)

79

2.05 Quiz – Correct Answer1. Open and submit the program m202a05 that calls

the autocall macro FREQ. Did the macro execute?

No, the default autocall location is SASAUTOS=SASAUTOS.

2. Uncomment the appropriate OPTION statement to modify the SASAUTOS= option and resubmit the program. Did the macro execute?

No, SAS will not search the autocall libraries for a member that was not found during an earlier search.

3. Add the MRECALL option and resubmit the program. Did the macro execute?

Yes, the MRECALL option causes SAS to search the autocall libraries again.

79 continued...

80

2.05 Quiz – Correct Answer4. Open the program FREQ, uncomment the %PUT

statements, and save the changed program.

5. Submit the following macro call:

Were the messages from the %PUT statements written to the log?

No, SAS will not recompile the FREQ macro after it is compiled successfully.

80 continued...

%freq(,Customer_Gender)

81

2.05 Quiz – Correct Answer6. Does the MRECALL option force the FREQ macro to

be recompiled?

No, the MRECALL option will not force a macro to recompile.

7. Submit the following %INCLUDE statement and macro call:

Were the messages from the %PUT statements written to the log?

Yes.

81

%include 'freq.sas';%freq(,Customer_Gender)

82

The Autocall Facility

82

Advantages of the Autocall Facility

Conditionally executed macros are compiled only if they are actually invoked.

You do not have to submit the source code for the macro definition before calling the macro.

You can set up multiple autocall libraries.

Macro definitions are easily viewed and edited with any text editor.

You can create a pool of easily maintained macros that different applications and users can access.

Disadvantages of the Autocall Facility

The macro must be compiled the first time that it is called in a SAS session.

83

Example 6: Store and Reuse MacrosThe Orion Star programmers plan to use the stored compiled macro facility for production-level jobs to save macro compilation time for macros that contain many macro statements.

83

84

Creating a Stored Compiled MacroThese steps create a permanently stored compiled macro:

1. Assign a libref to the SAS data library where the compiled macro is to be stored.

2. Set system options MSTORED and SASMSTORE=libref.

3. Submit the macro definition using the STORE option in the %MACRO statement.

84

85

Stored Compiled Macro Facility System OptionsThe MSTORED system option controls whether the stored compiled macro facility is available.

General form of the MSTORED system option:

The default option is NOMSTORED.

85

OPTIONS NOMSTORED | MSTORED;OPTIONS NOMSTORED | MSTORED;

86

Stored Compiled Macro Facility System OptionsThe SASMSTORE= system option controls where the macro facility looks for and writes stored compiled macros.

General form of the SASMSTORE= system option:

The libref points to an allocated SAS data library.

86

OPTIONS SASMSTORE=libref;OPTIONS SASMSTORE=libref;

87

USING the STORE, SOURCE, and DES= OptionsGeneral form of a stored compiled macro definition:

87

%MACRO macro-name (parameters) / STORE SOURCE DES='text' SECURE; macro-text%MEND macro-name;

%MACRO macro-name (parameters) / STORE SOURCE DES='text' SECURE; macro-text%MEND macro-name;

To do this… Use this option

store the compiled macro as a catalog entry in a permanent SAS library

STORE

store the source code of the macro, along with the compiled code, as an entry in a SAS catalog

SOURCE

specify a description for the macro entry in the macro catalog DES='text'

encrypt the stored compiled macro (The %COPY statement does not display the source code.)

SECURE

88

Accessing Stored Macro Source CodeUse a %COPY statement to retrieve the source code of a compiled stored macro.

General form of the %COPY statement:

If the OUT= option is omitted, source code is written to the SAS log.

88

%COPY macro-name / SOURCE <OUT='external file'>;%COPY macro-name / SOURCE <OUT='external file'>;

8989

90

2.06 Quiz1. Open the program m202a06. Add the STORE and

SOURCE options to the %MACRO statement.

2. Write a %COPY statement to view the source code in the log.

90

%macro freq(dsn, tablevar)/store source;

91

2.06 Quiz – Correct AnswerPartial SAS Log

91

60 options mstored sasmstore=sasuser;6162 %macro freq(dsn, tablevar)/store source;

. . . Lines removed . . . 74 %mend freq;7576 %copy freq / source;%macro freq(dsn, tablevar)/store source; %if &dsn = %then %do; %put You need to provide a data set name.; %return; %end; %if &tablevar = %then %do; %put You need to provide a table variable.; %return; %end; proc freq data = &dsn; tables &tablevar; run;%mend freq;

92

Using the SECURE OptionThe SECURE option can be used to write secure macros that will protect intellectual property that is contained in the macros.

92

%macro freq(dsn, tablevar)/store source secure; %if &dsn = %then %do; %put You need to provide a data set name.; %return; %end; %if &tablevar = %then %do; %put You need to provide a table variable.; %return; %end; proc freq data = &dsn; tables &tablevar; run;%mend freq;

m202d07

93

Using the SECURE OptionThere is no output produced when you use the %COPY statement.

93

%copy freq / source;

340 %copy freq / source;NOTE: The macro %FREQ was compiled with the /SECURE option. No output will be produced for this %COPY statement.

SAS Log

m202d07

94

Accessing Stored Compiled Macros

1. Assign a libref to the SAS data library containing a SASMACR catalog.

2. Set system options MSTORED and SASMSTORE=libref.

3. Call any macro stored in libref.SASMACR.

94

To access stored compiled macros, you must perform the following steps:

95

Accessing Stored Compiled Macros

95

Is PRINTDSN.MACRO in

WORK.SASMACRcatalog?

libref.SASMACRcatalog?

autocalllibrary?

Yes

Yes

Yes

No

No

No

Execute session-compiled PRINTDSN macro.

Execute storedcompiled PRINTDSN macro.

Compile and execute PRINTDSN autocall macro.

Requires MSTORED andSASMSTORE= system options

Requires MAUTOSOURCE and SASAUTOS= system options

WARNING: Apparent invocation of macro PRINTDSN not resolved.

96

Using a Stored Compiled MacroThe following are restrictions on stored compiled macros: You can only store compiled macros in the SASMACR

catalog. You should not rename this catalog or its entries. You cannot copy compiled macros across operating

systems or across releases of SAS. You must copy the source program and re-create the stored compiled macro.

96

97

Stored Compiled Macro Facility

97

Advantages of Stored Compiled Macros

SAS does not have to compile a macro definition when a macro call is made.

Users cannot modify compiled macros.

Session-compiled macros and the autocall facility are available in the same session.

Disadvantages of Stored Compiled Macros

Because you cannot edit a compiled macro, you must save and maintain the source for the macro definition.

There can be only one SASMACR catalog per library.

Stored compiled macros are not portable across operating environments.

98

Exercise

This exercise reinforces the concepts discussed previously.

98

9999

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)

100

Objectives Define the scope of a macro variable. Control the scope of a macro variable created

by the SYMPUTX routine.

100

101

Global versus Local Macro VariablesAlthough global macro variables are available for the duration of a SAS session, Orion Star wants to create local macro variables whenever possible.

Advantages of local macro variables include the following: conserve memory prevent accidentally updating a global macro variable's

value

101

102

Rules for Creating and Updating Variables (Review)When the macro processor receives a request to create or update a macro variable during macro execution, the macro processor follows these rules:

102

Does MACVAR already exist in a local table?

YesUpdate MACVAR in a local table.

Does MACVAR already exist in the global table?

Update MACVAR in the global table.

Create MACVAR in the local table.

No

No

Yes

%let macvar=value;

103

Rules for Resolving Variables (Review)To resolve a macro variable reference during macro execution, the macro processor follows these rules:

103

YesRetrieve from local table.

Retrieve from global table.

Return tokens to the word scanner. Issue a warning to the SAS log:Apparent symbolic reference MACVAR not resolved.

No

No

YesDoes MACVAR exist in the global table?

Does MACVAR exist in a local table?

&macvar

104

Resolving Variables in Nested Symbol Tables (Review)Multiple local tables can exist concurrently during macro execution. The search begins with the most local table and, if necessary, moves outward to the global table.

104

Global Table

MACRO1 Local Table

MACRO2 Local Table

MACRO4 Local Table

MACRO3 Local Table

105

Creating Local Macro Variables (Review)Local macro variables can be created within a macro definition by any of the following methods: %LET statement DATA step SYMPUTX routine PROC SQL SELECT statement INTO clause %LOCAL statement

Macros defined with parameters also create local macro variables.

105

106

Creating Local Macro VariablesThe Orion Star programmers want to ensure that the macro processor creates a local macro variable. They will use one of the following techniques: the %LOCAL statement the L argument for the SYMPUTX routine

106

107

The %LOCAL Statement (Review)General form of the %LOCAL statement:

The %LOCAL statement adds one or more macro variables to the local symbol table with null values.

It has no effect on variables already in the local table. It can appear only inside a macro definition.

107

%LOCAL macro-variable1 macro-variable2 …;%LOCAL macro-variable1 macro-variable2 …;

108

The SYMPUTX Routine (Review)The optional scope argument of the SYMPUTX routine specifies where to store the macro variable.

The value for scope can be one of the following:

108

CALL SYMPUTX(macro-variable, text <,scope>);CALL SYMPUTX(macro-variable, text <,scope>);

G specifies the global symbol table.

L specifies the current macro's local symbol table. If no local symbol table exists for the current macro, a local symbol table is created.

109109

110

2.07 Quiz1. Open the program m202a07. Submit the program and

examine the log messages. What are the problems with this program?

2. Insert the following %PUT statement after the RUN statement in the MAKELIST macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and COUNTRYNAME1

through COUNTRYNAME7 saved?

110

%put _user_;

111

2.07 Quiz – Correct Answer1. Open the program m202a07. Submit the program and

examine the log messages. What are the problems with this program?

The scope argument in the SYMPUTX routine forces the macro variables N, COUNTRY1 throughCOUNTRY 7, and COUNTRYNAME1 throughCOUNTRYNAME7 into the symbol table for the MAKELIST macro. Therefore, they are not available to the CUSTOMERS macro.

111 continued...

112

2.07 Quiz – Correct Answer2. Insert the following %PUT statement after the RUN

statement in the MAKELIST macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and

COUNTRYNAME1 through COUNTRYNAME7 saved?

MAKELIST

112

%put _user_;

113

Omitting the Scope Argument

113

If the SCOPE option is omitted and no local symbol tables exist, the SYMPUTX routine will store the macro variables in the global symbol table.

%macro makelist; data _null_; set orion.country end=final; call symputx(cats('country', _n_), Country); call symputx(cats('countryname', _n_), Country_Name); if final=1 then call symputx('n', _n_); run; %put _user_;%mend makelist;

m202d08

No scope specification

114

Omitting the Scope Argument

114

Partial Log

m202d08

25 %makelist

NOTE: There were 7 observations read from the data set ORION.COUNTRY.NOTE: DATA statement used (Total process time): real time 0.53 seconds cpu time 0.10 seconds

GLOBAL COUNTRY5 TRGLOBAL COUNTRY2 CAGLOBAL COUNTRY3 DEGLOBAL COUNTRY1 AUGLOBAL N 7GLOBAL COUNTRYNAME1 AustraliaGLOBAL COUNTRYNAME2 CanadaGLOBAL COUNTRYNAME3 GermanyGLOBAL COUNTRYNAME4 IsraelGLOBAL COUNTRYNAME5 TurkeyGLOBAL COUNTRYNAME6 United StatesGLOBAL COUNTRYNAME7 South AfricaGLOBAL COUNTRY6 USGLOBAL COUNTRY7 ZAGLOBAL COUNTRY4 IL

115115

116

2.08 Quiz1. Open the program m202a08. Delete the scope

argument from the three CALL SYMPUTX statements and insert the following %PUT statement after the %END statement in the CUSTOMERS macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and

COUNTRYNAME1 through COUNTRYNAME7 saved?

116

%put _user_;

117

2.08 Quiz – Correct Answer1. Open the program m202a08. Delete the scope

argument from the CALL SYMPUTX statement and insert the following %PUT statement after the %END statement in the CUSTOMERS macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and

COUNTRYNAME1 through COUNTRYNAME7 saved?

Global symbol table

117

%put _user_;

118

Correcting the Scope Issues with SYMPUTXThe Orion star programmers want to correct the scope problems with the SYMPUTX routine without creating global macro variables. To ensure the scope of the macro variables, they will use the following technique: omit the scope argument for the SYMPUTX routine use a %LOCAL statement

118

119

Correcting the Scope Issues with the SYMPUTX Routine

This demonstration illustrates how to correct the scope issues with the SYMPUTX routine.

119m202d09

120

Does the MAKELIST macro have a local table?

Correcting the Scope Issues with SYMPUTXIn some applications, the name and number of created macro variables might be unknown. Without the SCOPE argument, the SYMPUTX routine will store macro variables in the first symbol table that it encounters.

120

YesStore the macro variables in the MAKELIST symbol table.

Does the CUSTOMER macro have a local table?

Store the macro variables in the CUSTOMER symbol table.

Store the macro variables in the global symbol table.

No

No

Yes

call symputx(cats('country',_n_), Country);

121121

122

2.09 Quiz1. Open the program m202a09. Delete all macro variables

from the %LOCAL statement except for the macro variable I. Insert the following %PUT statement after the %END statement in the CUSTOMERS macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and

COUNTRYNAME1 through COUNTRYNAME7 saved?

2. Move the %LOCAL statement after the call to the MAKELIST macro. In which symbol table are the macro variables saved?

122

%put _user_;

123

2.09 Quiz – Correct Answer1. Open the program m202a09. Delete all macro

variables from the %LOCAL statement except for the macro variable I. Insert the following %PUT statement after the %END statement in the CUSTOMERS macro:

In which symbol table are the macro variables N,COUNTRY1 through COUNTRY 7, and

COUNTRYNAME1 through COUNTRYNAME7 saved?

CUSTOMERS symbol table

123

%put _user_;

continued...

124

2.09 Quiz – Correct Answer2. Move the %LOCAL statement after the call to the

MAKELIST macro. In which symbol table are the macro variables saved?

Global symbol table

124

125

The %SYMLOCAL FunctionThe %PUT statement is useful when you want to display the contents of a symbol table. To test whether a macro variable is in the local symbol table, the Orion Star programmers plan to use the %SYMLOCAL function.

General form of the %SYMLOCAL function:

The %SYMLOCAL function returns a value of 1 if the macro variable is found in a local symbol table and a 0 if not.

125

%SYMLOCAL(macro-variable-name)%SYMLOCAL(macro-variable-name)

126

The %SYMLOCAL FunctionPartial SAS Log

126

223 %macro scope;224 data _null_;225 call symputx('dog','Paisley','L');226 run;227 %if %symlocal(dog)=1 %then %put NOTE: DOG is in the local table.;228 %else %put WARNING: DOG is in the global table.;229 %mend scope;230231 %scope

NOTE: DOG is in the local table.232233 /* Omitting the scope argument on SYMPUTX */234 %macro scope;235 data _null_;236 call symputx('dog','Paisley');237 run;238 %if %symlocal(dog)=1 %then %put NOTE: DOG is in the local table.;239 %else %put WARNING: DOG is in the global table.;240 %mend scope;241242 %scope

WARNING: DOG is in the global table.

m202d10

127127

Chapter 2: Framework for Developing Macro Applications

2.1 Applying Best Practices

2.2 Debugging and Troubleshooting

2.3 Generating Custom Messages

2.4 Creating Efficient Macros

2.5 Understanding Symbol Tables

2.6 Creating Portable Applications (Self-Study)2.6 Creating Portable Applications (Self-Study)

128

Objectives Use automatic macro variables to identify the

operating environment. Use automatic macro variables to identify the version

of SAS. Use automatic macro variables to identify the software

that is currently licensed.

128

129

Defining PortabilityOrion Star has select macros that must run in multiple operating environments. The programmers plan to optimize a programmer’s development effort by designing portable macros.

Portable macro applications must identify the following information: the host environment(s) the version(s) of SAS currently licensed SAS software

129

130

Identifying the Host EnvironmentThe SYSSCP automatic macro variable stores the abbreviation of the host environment.

Values for SYSSCP include the following:

130

Value of SYSSCP

Operating System

WIN Windows XP, Vista, Server 2003, Server 2008

SUN 4 SOLARIS2 or SUN4.1.x

OS z/OS

131

Identifying the Host Environment The macro LIBASSIGN uses SYSSCP to determine the host platform and assigns a libref using the appropriate syntax for the operating environment.

131

%macro libassign; %local location; %if &sysscp=WIN %then %let location=s:\workshop; %else %if &sysscp=OS %then %let location=edu999.workshop.sasdata; %else %let location=/local/users/edu999;

libname orion "&location";%mend libassign;

m202d11

132

Identifying the Version of SASThe SYSVER automatic macro variable identifies the version of SAS software. It can be used to generate code that depends on the version.

The IN operator is new in SAS 9.2. The list of values is not enclosed in parentheses.

132m202d12

%if &sysver=9.2 %then %do; %let setinoption=options minoperator; %let ifvalue=&place in AU CA DE IL TR US ZA; %let resetinoption=options nominoperator; %end;%else %do; %let ifvalue=&place=AU or &place=CA or &place=DE or &place=IL or &place=TR or &place=US or &place=ZA; %end;

133

Identifying SAS Products Licensed The result of the %SYSPROD function indicates whether a product is licensed.

133m202d13

%macro chart; %local procname; %if %sysprod(graph) %then %let procname=gchart; %else %let procname=chart;

proc &procname data=orion.customer_dim; vbar Customer_Age_Group; run; quit;%mend chart;%chart

top related