Google SAS Search

Add to Google

Friday, March 09, 2007

The =: Operator

Most people who are familiar with programming SAS are familiar with the equal colon operator ( =: ). There are a couple different colon operators in SAS, but in this post I am only talking about the comparison operator. The equal colon operator works much like the substr() function. It is used to compare substrings for equality.

Here is a quick little example:


data _null_;
x = 'abcdefg';
if x =: 'abc'
then put 'The substrings match.';
run;


As you can see if you run the little data step above the substring 'abc' matches in 'abcdefg'. A better way to think of it is that it "starts with" the substring. The same could also be accomplished by this statement:

if substr(x,1,3) = 'abc'
then put 'The substrings match.';


There is one big difference between the =: operator and using substr(). With the substr() function you tell it exactly how many characters to look for the substring. In the example above it was three. For the =: operator it has to figure out how many characters to search. It does this by (somewhat counter-intuitively) looking at _both_ sides of the operator to find the shortest length. Here is an example:

data _null_;
x = 'abcdefg';
if x =: 'abc'
then put 'The substrings match.';
run;


If you run the above data step you will see that they match. It looks a little funny because most of us assume that SAS is looking for 'abcdefg' within 'abc', but that's not really what's happening. SAS uses the shortest string to decide what to look for, no matter which side of the equals sign it is on.

Oh yeah, the =: operator also works in list context such as:

if x in: ('abc', 'xyz', 'def');


That's it for today's post. Happy coding!

2 comments:

  1. It works with lists even if the items in the list aren't the same length too. That can be handy for things like GPI codes and international telecom country and city codes.

    ReplyDelete