SAS macros can be written as functions that return a value. To write a macro as a function, you can only use macro language statements and all macro variables must be local. The %sysfunc() macro function is used extensively to extend what can otherwise be achieved. The line containing the macro value being returned should not include a semicolon.
Extracting attributes such the number of rows (nobs) or columns (nvars) from a SAS data set is a very common request. Those values and many more can be obtained by using the attrn() function but that requires the use of open() and close() functions.
Therefore wrapping the attrn() function inside of a SAS macro function makes a lot of sense. See the below code used to create the GetAttrn() macro function.
%macro getattrn( dsn =, attr = nobs ) ; %local dsid retval ; %let retval = . ; %let dsid = %sysfunc( open( &dsn. ) ) ; %if &dsid. %then %do ; %let retval = %sysfunc( attrn( &dsid., &attr. ) ) ; %let dsid = %sysfunc( close( &dsid. ) ) ; %end ; &retval. %mend ;
Because macro processor events take place prior to program compilation you can take advantage of this knowledge and assign a dimension to an array within a data step.
data attribs( drop = dsid ) ; modified = put( %getattrn( dsn = sashelp.class, attr = modte ), datetime. ) ; obs = %getattrn( dsn = sashelp.class ) ; vars = %getattrn( dsn = sashelp.class, attr = nvars ) ; array atype[ %getattrn( dsn = sashelp.class, attr= nvar ) ] $1 ; dsid = open( 'sashelp.class' ) ; if dsid then do ; do _n_ = 1 to dim( atype ) ; atype[ _n_ ] = vartype( dsid, _n_ ) ; end ; end ; run ;