Chapter 17

Macro Functions

Macro Functions

Dictionary

%BQUOTE and %NRBQUOTE Functions

%EVAL Function

%INDEX Function

%LENGTH Function

%NRBQUOTE Function

%NRQUOTE Function

%NRSTR Function

%QSCAN Function

%QSUBSTR Function

%QSYSFUNC Function

%QUOTE and %NRQUOTE Functions

%QUPCASE Function

%SCAN and %QSCAN Functions

%STR and %NRSTR Functions

%SUBSTR and %QSUBSTR Functions

%SUPERQ Function

%SYMEXIST Function

%SYMGLOBL Function

%SYMLOCAL Function

%SYSEVALF Function

%SYSMACEXEC Function

%SYSMACEXIST Function

%SYSMEXECDEPTH Function

%SYSMEXECNAME Function

%SYSFUNC and %QSYSFUNC Functions

%SYSGET Function

%SYSPROD Function

%UNQUOTE Function

%UPCASE and %QUPCASE Functions

Macro Functions

A macro language function processes one or more arguments and produces a result.

Dictionary

%BQUOTE and %NRBQUOTE Functions

Mask special characters and mnemonic operators in a resolved value at macro execution.

Type:

Macro quoting function

See:

%QUOTE and %NRQUOTE Functions” on page 258 and “%SUPERQ Function” on page 269

Syntax

%BQUOTE(character-string | text-expression)

%NRBQUOTE(character-string | text-expression)

Details

The %BQUOTE and %NRBQUOTE functions mask a character string or resolved value of a text expression during execution of a macro or macro language statement. They mask the following special characters and mnemonic operators:

' " ( ) + − * / < > = ¬ ^ ~ ; , # blank
AND OR NOT EQ NE LE LT GE GT IN

In addition, %NRBQUOTE masks:

& %

%NRBQUOTE is most useful when the resolved value of an argument might contain

• strings that look like macro variable references but are not, so the macro processor should not attempt to resolve them when it next encounters them.

• macro invocations that you do not want the macro processor to attempt to resolve when it next encounters them.

Note: The maximum level of nesting for the macro quoting functions is 10.

Tip: You can use %BQUOTE and %NRBQUOTE for all execution-time macro quoting because they mask all characters and mnemonic operators that can be interpreted as elements of macro language.

Quotation marks (’") do not have to be marked.

For a description of quoting in SAS macro language, see “Macro Quoting” on page 84.

Comparisons

%NRBQUOTE and the %SUPERQ function mask the same items. However, %SUPERQ does not attempt to resolve a macro variable reference or a macro invocation that occurs in the value of the specified macro variable. %NRBQUOTE does attempt to resolve such references.%BQUOTE and %NRBQUOTE do not require that you mark quotation marks.

Example: Quoting a Variable

This example tests whether a filename passed to the macro FILEIT starts with a quotation mark. Based on that evaluation, the macro creates the correct FILE command.

%macro fileit(infile);
  %if %bquote(&infile) NE %then
     %do;
         %let char1 = %bquote(%substr(&infile,1,1));
         %if %bquote(&char1) = %str(%')
             or %bquote(&char1) = %str(%")
         %then %let command=FILE &infile;
         %else %let command=FILE "&infile";
     %end;
  %put &command;
%mend fileit;
%fileit(myfile)
%fileit('myfile')

When this program executes, the following is written to the log:

FILE "myfile"
FILE 'myfile'

%EVAL Function

Evaluates arithmetic and logical expressions using integer arithmetic.

Type:

Macro evaluation function

See:

%SYSEVALF Function” on page 273

Syntax

%EVAL(arithmetic | logical-expression)

Details

The %EVAL function evaluates integer arithmetic or logical expressions. %EVAL operates by converting its argument from a character value to a numeric or logical expression. Then, it performs the evaluation. Finally, %EVAL converts the result back to a character value and returns that value.

If all operands can be interpreted as integers, the expression is treated as arithmetic. If at least one operand cannot be interpreted as numeric, the expression is treated as logical. If a division operation results in a fraction, the fraction is truncated to an integer.

Logical, or Boolean, expressions return a value that is evaluated as true or false. In the macro language, any numeric value other than 0 is true and a value of 0 is false.

%EVAL accepts only operands in arithmetic expressions that represent integers (in standard or hexadecimal form). Operands that contain a period character cause an error when they are part of an integer arithmetic expression. The following examples show correct and incorrect usage, respectively:

%let d=%eval(10+20);      /* Correct usage  */

%let d=%eval(10.0+20.0);  /* Incorrect usage */

Because %EVAL does not convert a value containing a period to a number, the operands are evaluated as character operands. When %EVAL encounters a value containing a period, it displays an error message about finding a character operand where a numeric operand is required.

An expression that compares character values in the %EVAL function uses the sort sequence of the operating environment for the comparison. For more information about operating environment sort sequences, see “The SORT PROCEDURE” in the Base SAS Procedures Guide.

All parts of the macro language that evaluate expressions (for example, %IF and %DO statements) call %EVAL to evaluate the condition. For a complete discussion of how macro expressions are evaluated, see “Macro Expressions” on page 75.

Comparisons

%EVAL performs integer evaluations, but %SYSEVALF performs floating point evaluations.

Examples

Example 1: Illustrating Integer Arithmetic Evaluation

These statements illustrate different types of evaluations:

%let a=1+2;
%let b=10*3;
%let c=5/3;
%let eval_a=%eval(&a);
%let eval_b=%eval(&b);
%let eval_c=%eval(&c);
%put &a is &eval_a;
%put &b is &eval_b;
%put &c is &eval_c;

When these statements are submitted, the following is written to the SAS log:

1+2 is 3
10*3 is 30
5/3 is 1

The third %PUT statement shows that %EVAL discards the fractional part when it performs division on integers that would result in a fraction:

Example 2: Incrementing a Counter

The macro TEST uses %EVAL to increment the value of the macro variable I by 1. Also, the %DO %WHILE statement calls %EVAL to evaluate whether I is greater than the value of the macro variable FINISH.

%macro test(finish);
   %let i=1;
   %do %while (&i<&finish);
     %put the value of i is &i;
     %let i=%eval(&i+1);
   %end;
%mend test;
%test(5)

When this program executes, these lines are written to the SAS log:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4

Example 3: Evaluating Logical Expressions

Macro COMPARE compares two numbers.

%macro compare(first,second);
   %if &first>&second %then %put &first > &second;
   %else %if &first=&second %then %put &first = &second;
   %else %put &first<&second;
%mend compare;
%compare(1,2)
%compare(-1,0)

When this program executes, these lines are written to the SAS log:

1 < 2
-1 < 0

%INDEX Function

Returns the position of the first character of a string.

Type:

Macro function

Syntax

%INDEX(source, string)

Required Arguments

source

is a character string or text expression.

string

is a character string or text expression.

Details

The %INDEX function searches source for the first occurrence of string and returns the position of its first character. If string is not found, the function returns 0.

Example: Locating a Character

The following statements find the first character V in a string:

%let a=a very long value;
%let b=%index(&a,v);
%put V appears at position &b..;

When these statements execute, the following line is written to the SAS log:

V appears at position 3.

%LENGTH Function

Returns the length of a string.

Type:

Macro function

Syntax

%LENGTH(character-string | text-expression)

Details

If the argument is a character string, %LENGTH returns the length of the string. If the argument is a text expression, %LENGTH returns the length of the resolved value. If the argument has a null value, %LENGTH returns 0.

Example: Returning String Lengths

The following statements find the lengths of character strings and text expressions.

%let a=Happy;
%let b=Birthday;
%put The length of &a is %length(&a).;
%put The length of &b is %length(&b).;
%put The length of &a &b To You is %length(&a &b to you).;

When these statements execute, the following is written to the SAS log:

The length of Happy is 5.
The length of Birthday is 8.
The length of Happy Birthday To You is 21.

%NRBQUOTE Function

Masks special characters, including & and %, and mnemonic operators in a resolved value at macro execution.

Type:

Macro quoting function

See:

%BQUOTE and %NRBQUOTE Functions” on page 252

Syntax

%NRBQUOTE(character-string | text-expression)

Without Arguments

Note that the maximum level of nesting for the macro quoting functions is 10.

%NRQUOTE Function

Masks special characters, including & and %, and mnemonic operators in a resolved value at macro execution.

Type:

Macro quoting function

See:

%QUOTE and %NRQUOTE Functions” on page 258

Syntax

%NRQUOTE(character-string | text-expression)

Without Arguments

Note that the maximum level of nesting for the macro quoting functions is 10.

%NRSTR Function

Masks special characters, including & and %, and mnemonic operators in constant text during macro compilation.

Type:

Macro quoting function

See:

%STR and %NRSTR Functions” on page 264

Syntax

%NRSTR(character-string)

Without Arguments

Note that the maximum level of nesting for the macro quoting functions is 10.

%QSCAN Function

Searches for a word and masks special characters and mnemonic operators.

Type:

Macro function

Syntax

%QSCAN(argument,n<,charlist<,modifiers> >)

Without Arguments

%SCAN and %QSCAN Functions” on page 260

%QSUBSTR Function

Produces a substring and masks special characters and mnemonic operators.

Type:

Macro function

Syntax

%QSUBSTR(argument, position<, length>)

Without Arguments

See “%SUBSTR and %QSUBSTR Functions” on page 267

%QSYSFUNC Function

Executes functions and masks special characters and mnemonic operators.

Type:

Macro function

Syntax

%QSYSFUNC(function(argument(s))<, format>)

Without Arguments

See“%SYSFUNC and %QSYSFUNC Functions” on page 278

%QUOTE and %NRQUOTE Functions

Mask special characters and mnemonic operators in a resolved value at macro execution.

Type:

Macro quoting function

See:

%BQUOTE and %NRBQUOTE Functions” on page 252, “%NRBQUOTE Function” on page 256, “%NRSTR Function” on page 257, and “%SUPERQ Function” on page 269

Syntax

%QUOTE(character-string | text-expression)

%NRQUOTE(character-string | text-expression)

Details

The %QUOTE and %NRQUOTE functions mask a character string or resolved value of a text expression during execution of a macro or macro language statement. They mask the following special characters and mnemonic operators:

+ − * / < > = ¬ ^ ~ ; , # blank
AND OR NOT EQ NE LE LT GE GT IN

They also mask the following characters when they occur in pairs and when they are not matched and are marked by a preceding %

' "

In addition, %NRQUOTE masks

& %

%NRQUOTE is most useful when an argument might contain a macro variable reference or macro invocation that you do not want resolved.

For a description of quoting in SAS macro language, see “Macro Quoting” on page 84.

Note that the maximum level of nesting for the macro quoting functions is 10.

Comparisons

• %QUOTE and %NRQUOTE mask the same items as %STR and %NRSTR, respectively. However, %STR and %NRSTR mask constant text instead of a resolved value. And, %STR and %NRSTR work when a macro compiles, and %QUOTE and %NRQUOTE work when a macro executes.

• The %BQUOTE and %NRBQUOTE functions do not require that quotation marks without a match be marked with a preceding %, and %QUOTE and %NRQUOTE do.

• %QUOTE and %NRQUOTE mask resolved values, and the %SUPERQ function prevents resolution of any macro invocations or macro variable references that might occur in a value.

Example: Quoting a Value That Might Contain a Mnemonic Operator

The macro DEPT1 receives abbreviations for states and therefore might receive the value OR for Oregon.

%macro dept1(state);
      /* without %quote -- problems might occur */
   %if &state=nc %then
       %put North Carolina Department of Revenue;
   %else %put Department of Revenue;
%mend dept1;
%dept1(or)

When the macro DEPT1 executes, the %IF condition executes a %EVAL function, which evaluates or as a logical operator in this expression. Then the macro processor produces an error message for an invalid operand in the expression or=nc.

The macro DEPT2 uses the %QUOTE function to treat characters that result from resolving &STATE as text:

%macro dept2(state);
      /* with %quote function--problems are prevented */
   %if %quote(&state)=nc %then
       %put North Carolina Department of Revenue;
   %else %put Department of Revenue;
%mend dept2;
%dept2(or)

The %IF condition now compares the strings or and nc and writes to the SAS log:

Department of Revenue

%QUPCASE Function

Converts a value to uppercase and returns a result that masks special characters and mnemonic operators.

Type:

Macro function

Syntax

%QUPCASE(character-string | text-expression)

Without Arguments

See “%UPCASE and %QUPCASE Functions” on page 285

%SCAN and %QSCAN Functions

Search for a word that is specified by its position in a string.

Type:

Macro function

See:

%NRBQUOTE Function” on page 256 and “%STR and %NRSTR Functions” on page 264

Syntax

%SCAN(argument, n<,charlist <,modifiers> >)

%QSCAN(argument, n<,charlist <,modifiers> >)

Required Arguments

argument

is a character string or a text expression. If argument might contain a special character or mnemonic operator, listed below, use %QSCAN. If argument contains a comma, enclose argument in a quoting function such as %BQUOTE(argument).

n

is an integer or a text expression that yields an integer, which specifies the position of the word to return. (An implied %EVAL gives n numeric properties.) If n is greater than the number of words in argument, the functions return a null string.

Note: When you are using Version 8 or greater, if n is negative, %SCAN examines the character string and selects the word that starts at the end of the string and searches backward.

charlist

specifies an optional character expression that initializes a list of characters. This list determines which characters are used as the delimiters that separate words. The following rules apply:

• By default, all characters in charlist are used as delimiters.

• If you specify the K modifier in the modifier argument, then all characters that are not in charlist are used as delimiters.

Tip You can add more characters to charlist by using other modifiers.

modifier

specifies a character constant, a variable, or an expression in which each non-blank character modifies the action of the %SCAN function. Blanks are ignored. You can use the following characters as modifiers:

a or A

adds alphabetic characters to the list of characters.

b or B

scans backward from right to left instead of from left to right, regardless of the sign of the count argument.

c or C

adds control characters to the list of characters.

d or D

adds digits to the list of characters.

f or F

adds an underscore and English letters (that is, valid first characters in a SAS variable name using VALIDVARNAME=V7) to the list of characters.

g or G

adds graphic characters to the list of characters. Graphic characters are characters that, when printed, produce an image on paper.

h or H

adds a horizontal tab to the list of characters.

i or I

ignores the case of the characters.

k or K

causes all characters that are not in the list of characters to be treated as delimiters. That is, if K is specified, then characters that are in the list of characters are kept in the returned value rather than being omitted because they are delimiters. If K is not specified, then all characters that are in the list of characters are treated as delimiters.

l or L

adds lowercase letters to the list of characters.

m or M

specifies that multiple consecutive delimiters, and delimiters at the beginning or end of the string argument, refer to words that have a length of zero. If the M modifier is not specified, then multiple consecutive delimiters are treated as one delimiter, and delimiters at the beginning or end of the string argument are ignored.

n or N

adds digits, an underscore, and English letters (that is, the characters that can appear in a SAS variable name using VALIDVARNAME=V7) to the list of characters.

o or O

processes the charlist and modifier arguments only once, rather than every time the %SCAN function is called. Using the O modifier in the DATA step (excluding WHERE clauses), or in the SQL procedure can make %SCAN run faster when you call it in a loop where the charlist and modifier arguments do not change. The O modifier applies separately to each instance of the %SCAN function in your SAS code, and does not cause all instances of the %SCAN function to use the same delimiters and modifiers.

p or P

adds punctuation marks to the list of characters.

q or Q

ignores delimiters that are inside of substrings that are enclosed in quotation marks. If the value of the string argument contains unmatched quotation marks, then scanning from left to right will produce different words than scanning from right to left.

r or R

removes leading and trailing blanks from the word that %SCAN returns. If you specify both the Q and R modifiers, then the %SCAN function first removes leading and trailing blanks from the word. Then, if the word begins with a quotation mark, %SCAN also removes one layer of quotation marks from the word.

s or S

adds space characters to the list of characters (blank, horizontal tab, vertical tab, carriage return, line feed, and form feed).

t or T

trims trailing blanks from the string and charlist arguments. If you want to remove trailing blanks from only one character argument instead of both character arguments, then use the TRIM function instead of the %SCAN function with the T modifier.

u or U

adds uppercase letters to the list of characters.

w or W

adds printable (writable) characters to the list of characters.

x or X

adds hexadecimal characters to the list of characters.

Tip If the modifier argument is a character constant, then enclose it in quotation marks. Specify multiple modifiers in a single set of quotation marks. A modifier argument can also be expressed as a character variable or expression.

Details

The %SCAN and %QSCAN functions search argument and return the nth word. A word is one or more characters separated by one or more delimiters.

%SCAN does not mask special characters or mnemonic operators in its result, even when the argument was previously masked by a macro quoting function. %QSCAN masks the following special characters and mnemonic operators in its result:

& % ' " ( ) + − * / < > = ¬ ^ ~ ; , # blank
AND OR NOT EQ NE LE LT GE GT IN

Definition of “Delimiter” and “Word”

A delimiter is any of several characters that are used to separate words. You can specify the delimiters in the charlist and modifier arguments.

If you specify the Q modifier, then delimiters inside of substrings that are enclosed in quotation marks are ignored.

In the %SCAN function, “word” refers to a substring that has all of the following characteristics:

• is bounded on the left by a delimiter or the beginning of the string

• is bounded on the right by a delimiter or the end of the string

• contains no delimiters

A word can have a length of zero if there are delimiters at the beginning or end of the string, or if the string contains two or more consecutive delimiters. However, the %SCAN function ignores words that have a length of zero unless you specify the M modifier.

Using Default Delimiters in ASCII and EBCDIC Environments

If you use the %SCAN function with only two arguments, then the default delimiters depend on whether your computer uses ASCII or EBCDIC characters.

• If your computer uses ASCII characters, then the default delimiters are as follows:

blank ! $ % & ( ) * + , - . / ; < ^¦

In ASCII environments that do not contain the ^ character, the %SCAN function uses the ~ character instead.

• If your computer uses EBCDIC characters, then the default delimiters are as follows:

blank ! $ % & ( ) * + , - . / ; < ¬ | ¢¦

If you use the modifier argument without specifying any characters as delimiters, then the only delimiters that will be used are delimiters that are defined by the modifier argument. In this case, the lists of default delimiters for ASCII and EBCDIC environments are not used. In other words, modifiers add to the list of delimiters that are specified by the charlist argument. Modifiers do not add to the list of default modifiers.

Using the %SCAN Function with the M Modifier

If you specify the M modifier, then the number of words in a string is defined as one plus the number of delimiters in the string. However, if you specify the Q modifier, delimiters that are inside quotation marks are ignored.

If you specify the M modifier, then the %SCAN function returns a word with a length of zero if one of the following conditions is true:

• The string begins with a delimiter and you request the first word.

• The string ends with a delimiter and you request the last word.

• The string contains two consecutive delimiters and you request the word that is between the two delimiters.

Using the %SCAN Function without the M Modifier

If you do not specify the M modifier, then the number of words in a string is defined as the number of maximal substrings of consecutive non-delimiters. However, if you specify the Q modifier, delimiters that are inside quotation marks are ignored.

If you do not specify the M modifier, then the %SCAN function does the following:

• ignores delimiters at the beginning or end of the string

• treats two or more consecutive delimiters as if they were a single delimiter

If the string contains no characters other than delimiters, or if you specify a count that is greater in absolute value than the number of words in the string, then the %SCAN function returns one of the following:

• a single blank when you call the %SCAN function from a DATA step

• a string with a length of zero when you call the %SCAN function from the macro processor

Using Null Arguments

The %SCAN function allows character arguments to be null. Null arguments are treated as character strings with a length of zero. Numeric arguments cannot be null.

Comparisons

%QSCAN masks the same characters as the %NRBQUOTE function.

Example: Comparing the Actions of %SCAN and %QSCAN

This example illustrates the actions of %SCAN and %QSCAN.

%macro a;

   aaaaaa
%mend a;
%macro b;
   bbbbbb
%mend b;
%macro c;
   cccccc
%mend c;
%let x=%nrstr(%a*%b*%c);
%put X: &x;
%put The third word in X, with SCAN: %scan(&x,3,*);
%put The third word in X, with QSCAN: %qscan(&x,3,*);

The %PUT statement writes these lines to the log:

X: %a*%b*%c
The third word in X, with SCAN: cccccc
The third word in X, with QSCAN: %c

%STR and %NRSTR Functions

Mask special characters and mnemonic operators in constant text at macro compilation.

Type:

Macro quoting function

See:

%NRQUOTE Function” on page 257

Syntax

%STR(character-string)

%NRSTR(character-string)

Details

The %STR and %NRSTR functions mask a character string during compilation of a macro or macro language statement. They mask the following special characters and mnemonic operators:

+ − * / < > = ¬ ^ ~ ; ,  # blank
AND OR NOT EQ NE LE LT GE GT IN

They also mask the following characters when they occur in pairs and when they are not matched and are marked by a preceding %

' " ( )

In addition, %NRSTR also masks the following characters:

& %

Table 17.1 Using %STR and %NSTR Arguments

Argument

Use

Percent sign before a quotation mark - for example, %’ or %”,

Percent sign with quotation mark

EXAMPLE: %let percent=%str(Jim%’s office);

Percent sign before a parenthesis - for example, %( or %)

Two percent signs (%%):

EXAMPLE: %let x=%str(20%%);

Character string with the comment symbols /* or -->

%STR with each character

EXAMPLE: %str(/) %str(*) comment-text %str(*)%str(/)

%STR is most useful for character strings that contain

• a semicolon that should be treated as text rather than as part of a macro program statement

• blanks that are significant

• a quotation mark or parenthesis without a match

Putting the same argument within nested %STR and %QUOTE functions is redundant. This example shows an argument that is masked at macro compilation by the %STR function and remains masked at macro execution. Thus, in this example, the %QUOTE function used here has no effect.

%quote(%str(argument))

CAUTION:

Do not use %STR to enclose other macro functions or macro invocations that have a list of parameter values. Because %STR masks parentheses without a match, the macro processor does not recognize the arguments of a function or the parameter values of a macro invocation.

For a description of quoting in SAS macro language, see “Macro Quoting” on page 84.

Note: The maximum level of nesting for macro quoting functions is 10.

Comparisons

• Of all the macro quoting functions, only %NRSTR and %STR take effect during compilation. The other macro quoting functions take effect when a macro executes.

• %STR and %NRSTR mask the same items as %QUOTE and %NRQUOTE. However, %QUOTE and %NRQUOTE work during macro execution.

• If resolution of a macro expression produces items that need to be masked, use the %BQUOTE or %NRBQUOTE function instead of the %STR or %NRSTR function.

Examples

Example 1: Maintaining Leading Blanks

This example enables the value of the macro variable TIME to contain leading blanks.

%let time=%str(  now);
%put Text followed by the value of time:&time;

When this example is executed, these lines are written to the SAS log:

Text followed by the value of time:  now

Example 2: Protecting a Blank So That It Will Be Compiled as Text

This example specifies that %QSCAN use a blank as the delimiter between words.

%macro words(string);
   %local count word;
   %let count=1;
   %let word=%qscan(&string,&count,%str( ));
   %do %while(&word ne);
      %let count=%eval(&count+1);
      %let word=%qscan(&string,&count,%str( ));
   %end;
   %let count=%eval(&count-1);
   %put The string contains &count words.;
%mend words;
%words(This is a very long string)

When this program executes, these lines are written to the SAS log:

The string contains 6 words.

Example 3: Quoting a Value That Might Contain a Macro Reference

The macro REVRS reverses the characters produced by the macro TEST. %NRSTR in the %PUT statement protects %test&test so that it is compiled as text and not interpreted.

%macro revrs(string);
   %local nstring;
   %do i=%length(&string) %to 1 %by -1;
      %let nstring=&nstring%qsubstr(&string,&i,1);
   %end;
 &nstring
%mend revrs;
%macro test;
   Two words
%mend test;
%put %nrstr(%test%test) - %revrs(%test%test);

When this program executes, the following lines are written to the SAS log:

1          %macro revrs(string);
2             %local nstring;
3             %do i=%length(&string) %to 1 %by -1;
4                %let nstring=&nstring%qsubstr(&string,&i,1);
5             %end;&nstring
6          %mend revrs;
7
8          %macro test;
9             Two words
10         %mend test;
11
12         %put %nrstr(%test%test) - %revrs(%test%test);
%test%test - sdrow owTsdrow owT

NOTE: SAS Institute Inc., SAS Campus Drive, Cary, NC USA 27513-2414
NOTE: The SAS System used:
      real time           0.28 seconds
      cpu time            0.12 seconds

%SUBSTR and %QSUBSTR Functions

Produce a substring of a character string.

Type:

Macro function

See:

%NRBQUOTE Function” on page 256

Syntax

%SUBSTR(argument, position<, length>)

%QSUBSTR(argument, position<, length>)

Required Arguments

argument

is a character string or a text expression. If argument might contain a special character or mnemonic operator, listed below, use %QSUBSTR.

position

is an integer or an expression (text, logical, or arithmetic) that yields an integer, which specifies the position of the first character in the substring. If position is greater than the number of characters in the string, %SUBSTR and %QSUBSTR issue a warning message and return a null value. An automatic call to %EVAL causes n to be treated as a numeric value.

length

is an optional integer or an expression (text, logical, or arithmetic) that yields an integer that specifies the number of characters in the substring. If length is greater than the number of characters following position in argument, %SUBSTR and %QSUBSTR issue a warning message and return a substring containing the characters from position to the end of the string. By default, %SUBSTR and %QSUBSTR produce a string containing the characters from position to the end of the character string.

Details

The %SUBSTR and %QSUBSTR functions produce a substring of argument, beginning at position, for length number of characters.

%SUBSTR does not mask special characters or mnemonic operators in its result, even when the argument was previously masked by a macro quoting function. %QSUBSTR masks the following special characters and mnemonic operators:

& % ' " ( ) + − * / < > = ¬ ^ ~ ; , #  blank
AND OR NOT EQ NE LE LT GE GT IN

Comparisons

%QSUBSTR masks the same characters as the %NRBQUOTE function.

Examples

Example 1: Limiting a Fileref to Eight Characters

The macro MAKEFREF uses %SUBSTR to assign the first eight characters of a parameter as a fileref, in case a user assigns one that is longer.

%macro makefref(fileref,file);
   %if %length(&fileref) gt 8 %then
       %let fileref = %substr(&fileref,1,8);
   filename &fileref "&file";
%mend makefref;
%makefref(humanresource,/dept/humanresource/report96)

SAS sees the following statement:

FILENAME HUMANRES "/dept/humanresource/report96";

Example 2: Storing a Long Macro Variable Value in Segments

The macro SEPMSG separates the value of the macro variable MSG into 40-character units and stores each unit in a separate variable.

%macro sepmsg(msg);
   %let i=1;
   %let start=1;
   %if %length(&msg)>40 %then
      %do;
          %do %until(%length(&&msg&i)<40);
             %let msg&i=%qsubstr(&msg,&start,40);
             %put Message &i is: &&msg&i;
             %let i=%eval(&i+1);
             %let start=%eval(&start+40);
             %let msg&i=%qsubstr(&msg,&start);
          %end;
          %put Message &i is: &&msg&i;
      %end;
   %else %put No subdivision was needed.;
%mend sepmsg;
%sepmsg(%nrstr(A character operand was found in the %EVAL function
or %IF condition where a numeric operand is required.  A character
operand was found in the %EVAL function or %IF condition where a
numeric operand is required.));

When this program executes, these lines are written to the SAS log:

Message 1 is: A character operand was found in the %EV
Message 2 is: AL function or  %IF condition where a nu
Message 3 is: meric operand is required.  A character
Message 4 is: operand was  found in the %EVAL function
Message 5 is:  or %IF condition where a numeric operan
Message 6 is: d is required.

Example 3: Comparing Actions of %SUBSTR and %QSUBSTR

Because the value of C is masked by %NRSTR, the value is not resolved at compilation. %SUBSTR produces a resolved result because it does not mask special characters and mnemonic operators in C before processing it, even though the value of C had previously been masked with the %NRSTR function.

%let a=one;

%let b=two;
%let c=%nrstr(&a &b);
%put C: &c;
%put With SUBSTR: %substr(&c,1,2);
%put With QSUBSTR: %qsubstr(&c,1,2);

When these statements execute, these lines are written to the SAS log:

C: &a &b
With SUBSTR: one
With QSUBSTR: &a

%SUPERQ Function

Masks all special characters and mnemonic operators at macro execution but prevents further resolution of the value.

Type:

Macro quoting function

See:

%NRBQUOTE Function” on page 256 and “%BQUOTE and %NRBQUOTE Functions” on page 252

Syntax

%SUPERQ(argument)

Required Argument

argument

is the name of a macro variable with no leading ampersand or a text expression that produces the name of a macro variable with no leading ampersand.

Details

The %SUPERQ function returns the value of a macro variable without attempting to resolve any macros or macro variable references in the value. %SUPERQ masks the following special characters and mnemonic operators:

& % ' " ( ) + − * / < > = ¬ ^ ~ ; , #  blank
AND OR NOT EQ NE LE LT GE GT IN

%SUPERQ is particularly useful for masking macro variables that might contain an ampersand or a percent sign when they are used with the %INPUT or %WINDOW statement, or the SYMPUT routine.

For a description of quoting in SAS macro language, see “Macro Quoting” on page 84.

Note: The maximum level of nesting for the macro quoting functions is 10.

Comparisons

• %SUPERQ is the only quoting function that prevents the resolution of macro variables and macro references in the value of the specified macro variable.

• %SUPERQ accepts only the name of a macro variable as its argument, without an ampersand, and the other quoting functions accept any text expression, including constant text, as an argument.

• %SUPERQ masks the same characters as the %NRBQUOTE function. However, %SUPERQ does not attempt to resolve anything in the value of a macro variable. %NRBQUOTE attempts to resolve any macro references or macro variable values in the argument before masking the result.

Example: Passing Unresolved Macro Variable Values

In this example, %SUPERQ prevents the macro processor from attempting to resolve macro references in the values of MV1 and MV2 before assigning them to macro variables TESTMV1 and TESTMV2.

data _null_;
   call symput('mv1','Smith&Jones'),
   call symput('mv2','%macro abc;'),
run;
%let testmv1=%superq(mv1);
%let testmv2=%superq(mv2);
%put Macro variable TESTMV1 is &testmv1;
%put Macro variable TESTMV2 is &testmv2;

When this program executes, these lines are written to the SAS log:

Macro variable TESTMV1 is Smith&Jones
Macro variable TESTMV2 is %macro abc;

You might think of the values of TESTMV1 and TESTMV2 as “pictures” of the original values of MV1 and MV2. The %PUT statement then writes the pictures in its text. The macro processor does not attempt resolution. It does not issue a warning message for the unresolved reference &JONES or an error message for beginning a macro definition inside a %LET statement.

%SYMEXIST Function

Returns an indication of the existence of a macro variable.

Type:

Macro function

Syntax

%SYMEXIST(macro-variable-name)

Required Argument

macro-variable-name

is the name of a macro variable or a text expression that yields the name of a macro variable.

Details

The %SYMEXIST function searches any enclosing local symbol tables and then the global symbol table for the indicated macro variable and returns one of the following values:

1 if the macro variable is found

0 if the macro variable is not found

Example: Using %SYMEXIST Macro Function

The following example uses the %IF %THEN %ELSE macro statement to change the value of 1 and 0 to TRUE and FALSE respectively:

%global x;
%macro test;
    %local y;
        %if %symexist(x) %then %put %nrstr(%symexist(x)) = TRUE;
                         %else %put %nrstr(%symexist(x)) = FALSE;
        %if %symexist(y) %then %put %nrstr(%symexist(y)) = TRUE;
                         %else %put %nrstr(%symexist(y)) = FALSE;
        %if %symexist(z) %then %put %nrstr(%symexist(z)) = TRUE;
                         %else %put %nrstr(%symexist(z)) = FALSE;
%mend test;
%test;

In the previous example, executing the %TEST macro writes the following output to the SAS log:

%symexist(x) = TRUE
%symexist(y) = TRUE
%symexist(z) = FALSE

%SYMGLOBL Function

Returns an indication as to whether a macro variable is global in scope.

Type:

Macro function

Syntax

%SYMGLOBL(macro-variable-name)

Required Argument

macro-variable-name

is a name of a macro variable or a text expression that yields the name of a macro variable.

Details

The %SYMGLOBL function searches enclosing scopes for the indicated macro variable and returns a value of 1 if the macro variable is found in the global symbol table, otherwise it returns a 0. See “Scopes of Macro Variables” on page 47 for more information about the global and local symbol tables and macro variable scopes.

Example: Using %SYMGLOBL Macro Function

The following example uses the %IF %THEN %ELSE macro statement to change the values of 1 and 0 to TRUE and FALSE respectively:

%global x;

  %macro test;
      %local y;
      %if %symglobl(x) %then %put %nrstr(%symglobl(x)) = TRUE;
                       %else %put %nrstr(%symglobl(x)) = FALSE;
      %if %symglobl(y) %then %put %nrstr(%symglobl(y)) = TRUE;
                       %else %put %nrstr(%symglobl(y)) = FALSE;
      %if %symglobl(z) %then %put %nrstr(%symglobl(z)) = TRUE;
                       %else %put %nrstr(%symglobl(z)) = FALSE;
%mend test;
%test;

In the example above, executing the %TEST macro writes the following output to the SAS log:

%symglobl(x) = TRUE
%symglobl(y) = FALSE
%symglobl(z) = FALSE

%SYMLOCAL Function

Returns an indication as to whether a macro variable is local in scope.

Type:

Macro function

Syntax

%SYMLOCAL(macro-variable-name)

Required Argument

macro-variable-name

is the name of a macro variable or a text expression that yields the name of a macro variable.

Details

The %SYMLOCAL searches enclosing scopes for the indicated macro variable and returns a value of 1 if the macro variable is found in a local symbol table, otherwise it returns a 0. See “Scopes of Macro Variables” on page 47 for more information about the global and local symbol tables and macro variable scopes.

Example: Using %SYMLOCAL Macro Function

The following example uses the %IF %THEN %ELSE macro statement to change the values of 1 and 0 to TRUE and FALSE respectively:

%global x;
%macro test;
    %local y;
        %if %symlocal(x) %then %put %nrstr(%symlocal(x)) = TRUE;
                         %else %put %nrstr(%symlocal(x)) = FALSE;
        %if %symlocal(y) %then %put %nrstr(%symlocal(y)) = TRUE;
                         %else %put %nrstr(%symlocal(y)) = FALSE;

        %if %symlocal(z) %then %put %nrstr(%symlocal(z)) = TRUE;
                         %else %put %nrstr(%symlocal(z)) = FALSE;
%mend test;
%test;

In the example above, executing the %TEST macro writes the following output to the SAS log:

%symlocal(x) = FALSE
%symlocal(y) = TRUE
%symlocal(z) = FALSE

%SYSEVALF Function

Evaluates arithmetic and logical expressions using floating-point arithmetic.

Type:

Macro function

See:

%EVAL Function” on page 253

Syntax

%SYSEVALF(expression<, conversion-type>)

Required Arguments

expression

is an arithmetic or logical expression to evaluate.

conversion-type

converts the value returned by %SYSEVALF to the type of value specified. The value can then be used in other expressions that require a value of that type. Conversion-type can be one of the following:

BOOLEAN

returns

• 0 if the result of the expression is 0 or missing

• 1 if the result is any other value.

Here is an example:

%sysevalf(1/3,boolean)   /* returns 1 */
%sysevalf(10+.,boolean)  /* returns 0 */

CEIL

returns a character value representing the smallest integer that is greater than or equal to the result of the expression. If the result is within 10—12 of an integer, the function returns a character value representing that integer. An expression containing a missing value returns a missing value along with a message noting that fact:

%sysevalf(1 + 1.1,ceil)      /* returns  3 */
%sysevalf(-1 -2.4,ceil)      /* returns −3 */
%sysevalf(-1 + 1.e-11,ceil)  /* returns  0 */
%sysevalf(10+.)              /* returns  . */

FLOOR

returns a character value representing the largest integer that is less than or equal to the result of the expression. If the result is within 10—12 of an integer, the function returns that integer. An expression with a missing value produces a missing value:

%sysevalf(-2.4,floor)       /* returns −3 */
%sysevalf(3,floor)          /* returns  3 */
%sysevalf(1.-1.e-13,floor)  /* returns  1 */
%sysevalf(.,floor)          /* returns  . */

INTEGER

returns a character value representing the integer portion of the result (truncates the decimal portion). If the result of the expression is within 10—12 of an integer, the function produces a character value representing that integer. If the result of the expression is positive, INTEGER returns the same result as FLOOR. If the result of the expression is negative, INTEGER returns the same result as CEIL. An expression with a missing value produces a missing value:

%put %sysevalf(2.1,integer);        /* returns  2 */
%put %sysevalf(-2.4,integer);       /* returns −2 */
%put %sysevalf(3,integer);          /* returns  3 */
%put %sysevalf(-1.6,integer);       /* returns −1 */
%put %sysevalf(1.-1.e-13,integer);  /* returns  1 */

Details

The %SYSEVALF function performs floating-point arithmetic and returns a value that is formatted using the BEST32. format. The result of the evaluation is always text. %SYSEVALF is the only macro function that can evaluate logical expressions that contain floating-point or missing values. Specify a conversion type to prevent problems when %SYSEVALF returns one of the following:

• missing or floating-point values to macro expressions

• macro variables that are used in other macro expressions that require an integer value

If the argument to the %SYSEVALF function contains no operator and no conversion type is specified, then the argument is returned unchanged.

For details about evaluation of expressions by the SAS macro language, see “Macro Expressions” on page 75.

Comparisons

• %SYSEVALF supports floating-point numbers. However, %EVAL performs only integer arithmetic.

• You must use the %SYSEVALF macro function in macros to evaluate floating-point expressions. However, %EVAL is used automatically by the macro processor to evaluate macro expressions.

Example: Illustrating Floating-Point Evaluation

The macro FIGUREIT performs all types of conversions for SYSEVALF values.

%macro figureit(a,b);
   %let y=%sysevalf(&a+&b);
   %put The result with SYSEVALF is: &y;
   %put  The BOOLEAN value is: %sysevalf(&a +&b, boolean);

   %put  The CEIL value is: %sysevalf(&a +&b, ceil);
   %put  The FLOOR value is: %sysevalf(&a +&b, floor);
   %put  The INTEGER value is: %sysevalf(&a +&b, int);
%mend figureit;
%figureit(100,1.597)

When this program executes, these lines are written to the SAS log:

The result with SYSEVALF is: 101.597
The BOOLEAN value is: 1
The CEIL value is: 102
The FLOOR value is: 101
The INTEGER value is: 101

%SYSMACEXEC Function

Returns an indication of the execution status of a macro.

Type:

Macro function

Syntax

%SYSMACEXEC(macro_name)

Required Argument

macro_name

the name of a macro or a text expression that yields the name of the macro.

Details

The %SYSMACEXEC function returns the number 1 if the macro is currently executing. Otherwise, if the macro is not executing, the number 0 is returned.

%SYSMACEXIST Function

Returns an indication of the existence of a macro definition in the Work.SASMacr catalog. Otherwise, the returned value is 0.

Type:

Macro function

Syntax

%SYSMACEXIST(macro-name)

Required Argument

macro-name

the name of a macro or a text expression that yields the name of a macro.

Details

The %SYSMACEXIST function returns the number 1 if a definition for the macro exists in the Work.SASMacr catalog. If there is not a macro definition, the returned value is 0.

%SYSMEXECDEPTH Function

Returns the nesting depth of macro execution from the point of the call to %SYSMEXECDEPTH.

Type:

Macro Function

Tip:

%SYSMEXECDEPTH and %SYSMEXECNAME were implemented to be used together, but it is not required.

See:

%SYSMEXECNAME Function

Syntax

%SYSMEXECDEPTH

Details

To retrieve the nesting level of the currently executing macro, use the %SYSMEXECDEPTH. This function returns a number indicating the depth of the macro in nested macro calls. The following are the %SYSMEXECDEPTH return value descriptions:

0    open code

>0  nesting level

See the following example and explanations that follow it.

8          %macro A;
9             %put %sysmexecdepth;
10         %mend A;  /* The macro execution depth
                                        of a macro called from open code */
11         %A;       /* is one  */
1
12
13         %macro B;
14            %put %nrstr(%%)sysmexecdepth=%sysmexecdepth;
15            %put %nrstr(%%)sysmexecname(1)=%sysmexecname(1);
16            %put %nrstr(%%)sysmexecname(2)=%sysmexecname(2);
17            %put %nrstr(%%)sysmexecname(0)=%sysmexecname(0);
18            %put %nrstr(%%)sysmexecname(%nrstr(%%)sysmexecdepth-1)=
                   %sysmexecname(%sysmexecdepth-1);
19         %mend B;
20         
21         %macro C;
22         %B;
23         %mend;
24         %C;
%sysmexecdepth=2
%sysmexecname(1)=C
%sysmexecname(2)=B

%sysmexecname(0)=OPEN CODE
%sysmexecname(%sysmexecdepth-1)=C
25
26         %macro level1;
27         %level2;
28         %mend;
29         %macro level2;
30         %level3;
31         %mend;
32         %macro level3;
33         %level4;
34         %mend;
35         %macro level4;
36         %do i = %sysmexecdepth+1 %to -1 %by -1;
37             %put %nrstr(%%)sysmexecname(&i)=%sysmexecname(&i);
38         %end;
39         %mend;
40
41         %level1;
WARNING: Argument 1 to %SYSMEXECNAME function is out of range.
%sysmexecname(5)=
%sysmexecname(4)=LEVEL4
%sysmexecname(3)=LEVEL3
%sysmexecname(2)=LEVEL2
%sysmexecname(1)=LEVEL1
%sysmexecname(0)=OPEN CODE
WARNING: Argument 1 to %SYSMEXECNAME function is out of range.
%sysmexecname(-1)=
42

• Macro A calls macro B. Macro C calls macro B. A call to %SYSMEXECDEPTH placed in macro C would return the value 2 for macro B.

• If the macro C wanted to know the name of the macro that had called it, it could call %SYSMEXECNAME with %SYSMEXECNAME(%SYSMEXECDEPTH-1 (the value of the n argument being %SYSMEXECDEPTH, its own nesting level, minus one). That call to %SYSMEXECNAME would return the value B.

%SYSMEXECNAME Function

Returns the name of the macro executing at a requested nesting level.

Type:

Macro Function

Tip:

%SYSMEXECNAME and %SYSMEXECDEPTH were implemented to be used together, but it is not required.

See:

%SYSMEXECDEPTH function

Syntax

%SYSMEXECNAME(n)

Required Argument

n

The nesting level at which you are requesting the macro name.

0    open code

>0  nesting level

Details

The %SYSMEXECNAME function returns the name of the macro executing at the n nesting level. The following three scenarios are shown in the example below.

• If n = 0, open code is returned.

• If n >%SYSMEXECDEPTH, a null string is returned and a WARNING diagnostic message is issued to the SAS log.

• If n<0, a null string is returned and a WARNING diagnostic message is issued to the SAS log.

3          %put %sysmexecdepth; /* The macro execution depth of
                                   Open Code is zero */
0
4          %put %sysmexecname(%sysmexecdepth);
OPEN CODE
5          %put %sysmexecname(%sysmexecdepth + 1);
WARNING: Argument 1 to %SYSMEXECNAME function is out of range.

6          %put %sysmexecname(%sysmexecdepth - 1);
WARNING: Argument 1 to %SYSMEXECNAME function is out of range.

%SYSFUNC and %QSYSFUNC Functions

Execute SAS functions or user-written functions.

Type:

Macro function

Tip:

%SYSFUNC and %QSYSFUNC support SAS function names up to 32 characters.

Syntax

%SYSFUNC(function(argument(s))<, format>)

%QSYSFUNC(function(argument(s))<, format>)

Required Arguments

function

is the name of the function to execute. This function can be a SAS function, a function written with SAS/TOOLKIT software, or a function created using the Chapter 21, “FCMP Procedure” in Base SAS Procedures Guide. The function cannot be a macro function.

All SAS functions, except those listed in Table 17.2 on page 279, can be used with %SYSFUNC and %QSYSFUNC.

You cannot nest functions to be used with a single %SYSFUNC. However, you can nest %SYSFUNC calls:

%let x=%sysfunc(trim(%sysfunc(left(&num))));

Syntax for Selected Functions Used with the %SYSFUNC Function on page 379 shows the syntax of SAS functions used with %SYSFUNC that were introduced with SAS 6.12.

argument(s)

is one or more arguments used by function. An argument can be a macro variable reference or a text expression that produces arguments for a function. If argument might contain a special character or mnemonic operator, listed below, use %QSYSFUNC.

format

is an optional format to apply to the result of function. This format can be provided by SAS, generated by PROC FORMAT, or created with SAS/TOOLKIT. There is no default value for format. If you do not specify a format, the SAS macro facility does not perform a format operation on the result and uses the default of the function.

Details

Because %SYSFUNC is a macro function, you do not need to enclose character values in quotation marks as you do in DATA step functions. For example, the arguments to the OPEN function are enclosed in quotation marks when the function is used alone, but do not require quotation marks when used within %SYSFUNC. These statements show the difference:

dsid=open("Sasuser.Houses","i");

dsid=open("&mydata","&mode");

%let dsid = %sysfunc(open(Sasuser.Houses,i));

%let dsid=%sysfunc(open(&mydata,&mode));

All arguments in DATA step functions within %SYSFUNC must be separated by commas. You cannot use argument lists preceded by the word OF.

Note: The arguments to %SYSFUNC are evaluated according to the rules of the SAS macro language. This includes both the function name and the argument list to the function. In particular, an empty argument position will not generate a NULL argument, but a zero length argument.

%SYSFUNC does not mask special characters or mnemonic operators in its result. %QSYSFUNC masks the following special characters and mnemonic operators in its result:

& % ' " ( ) + − * / < > = ¬ ^ ~ ; , #  blank
AND OR NOT EQ NE LE LT GE GT IN

When a function called by %SYSFUNC or %QSYSFUNC requires a numeric argument, the macro facility converts the argument to a numeric value. %SYSFUNC and %QSYSFUNC can return a floating point number when the function that they execute supports floating point numbers.

Table 17.2 SAS Functions Not Available with %SYSFUNC and %QSYSFUNC

All Variable Information Functions

ALLCOMB

ALLPERM

DIF

DIM

HBOUND

IORCMSG

INPUT

LAG

LBOUND

LEXCOMB

LEXCOMBI

LEXPERK

LEXPERM

MISSING

PUT

RESOLVE

SYMGET

Note: Instead of INPUT and PUT, which are not available with %SYSFUNC and %QSYSFUNC, use INPUTN, INPUTC, PUTN, and PUTC.

Note: The Variable Information functions include functions such as VNAME and VLABEL. For a complete list, see “Definitions of Functions and CALL Routines” in SAS Functions and CALL Routines: Reference.

CAUTION:

Values returned by SAS functions might be truncated. Although values returned by macro functions are not limited to the length imposed by the DATA step, values returned by SAS functions do have that limitation.

Comparisons

%QSYSFUNC masks the same characters as the %NRBQUOTE function.

Examples

Example 1: Formatting the Current Date in a TITLE Statement

This example formats a TITLE statement containing the current date using the DATE function and the WORDDATE. format:

title "%sysfunc(date(),worddate.) Absence Report";

When the program is executed on July 18, 2008, the statement produces the following TITLE statement:

title "July 18, 2008 Absence Report"

Example 2: Formatting a Value Produced by %SYSFUNC

In this example, the TRY macro transforms the value of PARM using the PUTN function and the CATEGORY. format.

proc format;
  value category
  Low-<0  = 'Less Than Zero'
  0       = 'Equal To Zero'
  0<-high = 'Greater Than Zero'
  other   = 'Missing';
run;
%macro try(parm);
  %put &parm is %sysfunc(putn(&parm,category.));

%mend;
%try(1.02)
%try(.)
%try(-.38)

When these statements are executed, these lines are written to the SAS log:

1.02 is Greater Than Zero
. is Missing
-.38 is Less Than Zero

Example 3: Translating Characters

%SYSFUNC executes the TRANSLATE function to translate the Ns in a string to Ps.

%let string1 = V01N01-V01N10;
%let string1 = %sysfunc(translate(&string1,P, N));
%put With N translated to P, V01N01-V01N10 is &string1;

When these statements are executed, these lines are written to the SAS log:

With N translated to P, V01N01-V01N10 is V01P01-V01P10

Example 4: Confirming the Existence of a SAS Data Set

The macro CHECKDS uses %SYSFUNC to execute the EXIST function, which checks the existence of a data set:

%macro checkds(dsn);
   %if %sysfunc(exist(&dsn)) %then
      %do;
         proc print data=&dsn;
         run;
   %end;
   %else
      %put The data set &dsn does not exist.;
%mend checkds;
%checkds(Sasuser.Houses)

When the program is executed, the following statements will be produced:

PROC PRINT DATA=SASUSER.HOUSES;
RUN;

Example 5: Determining the Number of Variables and Observations in a Data Set

Many solutions have been generated in the past to obtain the number of variables and observations present in a SAS data set. Most past solutions have used a combination of _NULL_ DATA steps, SET statement with NOBS=, and arrays to obtain this information. Now, you can use the OPEN and ATTRN functions to obtain this information quickly and without interfering with step boundary conditions.

%macro obsnvars(ds);
   %global dset nvars nobs;
   %let dset=&ds;
   %let dsid = %sysfunc(open(&dset));
   %if &dsid %then
      %do;
         %let nobs =%sysfunc(attrn(&dsid,NOBS));
         %let nvars=%sysfunc(attrn(&dsid,NVARS));
         %let rc = %sysfunc(close(&dsid));

         %put &dset has &nvars  variable(s) and &nobs observation(s).;
      %end;
   %else
      %put Open for data set &dset failed - %sysfunc(sysmsg());
%mend obsnvars;
%obsnvars(Sasuser.Houses)

When the program is executed, the following message will appear in the SAS log:

sasuser.houses has 6 variable(s) and 15 observation(s).

%SYSGET Function

Returns the value of the specified operating environment variable.

Type:

Macro function

Syntax

%SYSGET(environment-variable)

Required Argument

environment-variable

is the name of an environment variable. The case of environment-variable must agree with the case that is stored on the operating environment.

Details

The %SYSGET function returns the value as a character string. If the value is truncated or the variable is not defined on the operating environment, %SYSGET displays a warning message in the SAS log.

You can use the value returned by %SYSGET as a condition for determining further action to take or parts of a SAS program to execute. For example, your program can restrict certain processing or issue commands that are specific to a user.

For details, see the SAS documentation for your operating environment.

Example: Using SYSGET in a UNIX Operating Environment

This example returns the ID of a user on a UNIX operating environment:

%let person=%sysget(USER);
%put User is &person;

When these statements execute for user ABCDEF, the following is written to the SAS log:

User is abcdef

%SYSPROD Function

Reports whether a SAS software product is licensed at the site.

Type:

Macro function

See:

%SYSEXEC Statement” on page 328, “SYSSCP and SYSSCPL Automatic Macro Variables” on page 220, and “SYSVER Automatic Macro Variable” on page 228

Syntax

%SYSPROD(product)

Required Argument

product

can be a character string or text expression that yields a code for a SAS product. The following are commonly used codes:

Table 17.3 Commonly Used Codes

AF

CPE

GRAPH

PH-CLINICAL

ASSIST

EIS

IML

QC

BASE

ETS

INSIGHT

SHARE

CALC

FSP

LAB

STAT

CONNECT

GIS

OR

TOOLKIT

For codes for other SAS software products, see your on-site SAS support personnel.

Details

%SYSPROD can return the following values:

Table 17.4 %SYSPROD Values and Descriptions

Value

Description

1

The SAS product is licensed.

0

The SAS product is not licensed.

−1

The product is not Institute software (for example, if the product code is misspelled).

Example: Verifying SAS/GRAPH Installation Before Running the GPLOT Procedure

This example uses %SYSPROD to determine whether to execute a PROC GPLOT statement or a PROC PLOT statement, based on whether SAS/GRAPH software has been installed.

%macro runplot(ds);
   %if %sysprod(graph)=1 %then
      %do;
         title "GPLOT of %upcase(&ds)";
         proc gplot data=&ds;
            plot style*price / haxis=0 to 150000 by 50000;
         run;
         quit;
      %end;
   %else
      %do;
         title "PLOT of %upcase(&ds)";
         proc plot data=&ds;
            plot style*price;
         run;
         quit;
      %end;
%mend runplot;
%runplot(Sasuser.Houses)

When this program executes and SAS/GRAPH is installed, the following statements are generated:

TITLE "GPLOT of SASUSER.HOUSES";
PROC GPLOT DATA=SASUSER.HOUSES;
PLOT STYLE*PRICE / HAXIS=0 TO 150000 BY 50000;
RUN;

%UNQUOTE Function

During macro execution, unmasks all special characters and mnemonic operators for a value.

Type:

Macro function

See:

%BQUOTE and %NRBQUOTE Functions” on page 252, “%NRBQUOTE Function” on page 256, “%NRQUOTE Function” on page 257, “%NRSTR Function” on page 257, “%QUOTE and %NRQUOTE Functions” on page 258, “%STR and %NRSTR Functions” on page 264, and “%SUPERQ Function” on page 269

Syntax

%UNQUOTE(character-string | text-expression)

Details

The %UNQUOTE function unmasks a value so that special characters that it might contain are interpreted as macro language elements instead of as text. The most important effect of %UNQUOTE is to restore normal tokenization of a value whose tokenization was altered by a previous macro quoting function. %UNQUOTE takes effect during macro execution.

For more information, see “Macro Quoting” on page 84.

Example: Using %UNQUOTE to Unmask Values

This example demonstrates a problem that can arise when the value of a macro variable is assigned using a macro quoting function and then the variable is referenced in a later DATA step. If the value is not unmasked before it reaches the SAS compiler, the DATA step does not compile correctly and it produces error messages. Although several macro functions automatically unmask values, a variable might not be processed by one of those functions.

The following program generates error messages in the SAS log because the value of TESTVAL is still masked when it reaches the SAS compiler.

%let val = aaa;
%let testval = %str(%'&val%'),
data _null_;
  val = &testval;
  put 'VAL =' val;
run;

This version of the program runs correctly because %UNQUOTE unmasks the value of TESTVAL.

%let val = aaa;
%let testval = %str(%'&val%'),
data _null_;
  val = %unquote(&testval);
  put 'VAL =' val;
run;

This program prints the following to the SAS log:

VAL=aaa

%UPCASE and %QUPCASE Functions

Convert values to uppercase.

Type:

Macro function

See:

%LOWCASE and %QLOWCASE Autocall Macros” on page 184, “%NRBQUOTE Function” on page 256, and “%QLOWCASE Autocall Macro” on page 186

Syntax

%UPCASE(character-string | text-expression)

%QUPCASE(character-string | text-expression)

Details

The %UPCASE and %QUPCASE functions convert lowercase characters in the argument to uppercase. %UPCASE does not mask special characters or mnemonic operators in its result, even when the argument was previously masked by a macro quoting function.

If the argument contains a special character or mnemonic operator, listed below, use %QUPCASE. %QUPCASE masks the following special characters and mnemonic operators in its result:

& % ' " ( ) + − * / < > = ¬ ^ ~ ; , # blank
AND OR NOT EQ NE LE LT GE GT IN

%UPCASE and %QUPCASE are useful in the comparison of values because the macro facility does not automatically convert lowercase characters to uppercase before comparing values.

Comparisons

• %QUPCASE masks the same characters as the %NRBQUOTE function.

• To convert characters to lowercase, use the %LOWCASE or %QLOWCASE autocall macro.

Examples

Example 1: Capitalizing a Value to Be Compared

In this example, the macro RUNREPT compares a value input for the macro variable MONTH to the string DEC. If the uppercase value of the response is DEC, then PROC FSVIEW runs on the data set Reports.EndYear. Otherwise, PROC FSVIEW runs on the data set with the name of the month in the Reports data library.

%macro runrept(month);
   %if %upcase(&month)=DEC %then
       %str(proc fsview data=reports.endyear; run;);
   %else %str(proc fsview data=reports.&month; run;);
%mend runrept;

You can invoke the macro in any of these ways to satisfy the %IF condition:

%runrept(DEC)
%runrept(Dec)
%runrept(dec)

Example 2: Comparing %UPCASE and %QUPCASE

These statements show the results produced by %UPCASE and %QUPCASE:

%let a=begin;
%let b=%nrstr(&a);
%put UPCASE produces: %upcase(&b);
%put QUPCASE produces: %qupcase(&b);

When these statements execute, the following is written to the SAS log:

UPCASE produces: begin
QUPCASE produces: &A

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.86