Published on :
Macro CREATION_INTERNE

Macro _COUNT: Count Elements in a List

This code is also available in: Français Deutsch Español
This macro, named _COUNT, aims to determine the number of elements in a character string where elements are separated by a delimiter. By default, the delimiter is a space, but it can be changed via the 'SPLIT' parameter. The macro takes as input the list to analyze (positional parameter ARG1 or named TEXT). It has a 'NOTES' option to display the result directly in the SAS© log. A simple error handling mechanism is included to intercept 'Apparent symbolic reference' warnings and stop execution if necessary. The code also contains a commented validation test section that demonstrates various use cases.
Data Analysis

Type : CREATION_INTERNE


The macro does not read any external data or from the SASHELP library. It operates exclusively on character strings passed as parameters during its call.

1 Code Block
%PUT
Explanation :
Displays initial notes in the SAS log, including the call date and copyright information.
Copied!
1%put NOTE: You have called the macro _COUNT, 2022-06-07.;
2%put NOTE: Copyright (c) 2001-2022 Rodney Sparapani;
3 
2 Code Block
MACRO
Explanation :
Definition of the '_count' macro. It initializes a local counter 'i' to 0. Then, a '%do %while' loop iterates through the input string ('text') using the '%qscan' function to extract elements one by one, based on the 'split' delimiter. The counter 'i' is incremented for each element found. After the loop, the macro checks for a specific warning and stops in case of an issue. Otherwise, it returns the final value of the counter 'i'. If the 'notes' parameter is provided, the returned value is also displayed in the log.
Copied!
1%macro _count(arg1, text=&arg1, notes=, split=%str( ));
2 %local i;
3 %let i=0;
4 
5 %*DO %while(%LENGTH(%nrbquote(%scan(%nrbquote(&text), &i+1, &split))));
6 %DO %while(%LENGTH(%qscan(&text, &i+1, &split)));
7 %let i=%eval(&i+1);
8 %END;
9%IF "%_substr(%superq(syswarningtext), 1, 27)"="Apparent symbolic reference"
10%THEN %DO;
11 %put ERROR: _COUNT() cannot recover from warning: ABEND;
12 %_abend();
13%END;
14%ELSE &i;
15 
16 %IF %LENGTH(¬es) %THEN %put NOTE: _COUNT is returning the value: &i.;
17%mend _count;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Copyright (c) 2001-2022 Rodney Sparapani. The code is distributed under the terms of the GNU General Public License (GPL) version 2 or later.