DATA Step, Macro, Functions and more

%qsubstr

Accepted Solution Solved
Reply
Super Contributor
Posts: 271
Accepted Solution

%qsubstr

I wonder why this does not work.

 

data _null_;
	a = %qsubstr(12&34,1,4);
	put a;
run;

expected ouput : 12&3


Accepted Solutions
Solution
‎06-05-2017 05:05 PM
Super User
Posts: 7,760

Re: %qsubstr

Posted in reply to SAS_inquisitive

After resolution of the macro function, you get this data step:

data _null_;
  a = 12&3;
  put a;
run;

& is a mnemonic for the boolean "and" operator, so the SAS interpreter sees the 12 and the 3 as boolean values; since both are non-zero, this resolves to the boolean expression "true and true", so the result is "true", which is represented in SAS by 1.

 

If you wanted a to be the string "12&3", you would have needed to write

data _null_;
  a = "%qsubstr(12&34,1,4)";
  put a;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers

View solution in original post


All Replies
Super User
Posts: 5,497

Re: %qsubstr

[ Edited ]
Posted in reply to SAS_inquisitive

Macro functions are not part of a DATA step.  You might as well have coded:

 

data _null_;
a = 12&34,1,4;
put a;
run;

 

Note that Kurt is right about what you get when you do use %QSUBSTR ... 12&3 (not what I posted above).  Now that will get resolved by as DATA step into the number 1.  12 is true, 3 is true, so 12 & 3 is true and gets resolved to 1.

 

In a DATA step,  you might simply use:

 

data _null_;
a = substr('12&34',1,4);
put a;
run;

 

Single quotes always turn off macro processing, whether in a DATA step or in macro language statements.

Solution
‎06-05-2017 05:05 PM
Super User
Posts: 7,760

Re: %qsubstr

Posted in reply to SAS_inquisitive

After resolution of the macro function, you get this data step:

data _null_;
  a = 12&3;
  put a;
run;

& is a mnemonic for the boolean "and" operator, so the SAS interpreter sees the 12 and the 3 as boolean values; since both are non-zero, this resolves to the boolean expression "true and true", so the result is "true", which is represented in SAS by 1.

 

If you wanted a to be the string "12&3", you would have needed to write

data _null_;
  a = "%qsubstr(12&34,1,4)";
  put a;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Super Contributor
Posts: 271

Re: %qsubstr

Posted in reply to KurtBremser

Thank you both for great explanation.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 155 views
  • 2 likes
  • 3 in conversation