BookmarkSubscribeRSS Feed
sanyam13
Fluorite | Level 6

 

can you plz explain how come the length of variable sec is 25 ? 

 

data test;
first = 'ipswich, england';
sec = substr(first,1,7)!!','!!'England';
run;

3 REPLIES 3
RW9
Diamond | Level 26 RW9
Diamond | Level 26

It is because you have not explicitly set any lengths SAS uses its defaults.

So:
first is set to 16 as that is the length of the first string applied to it.

Then the substr is called, and logically the maximum value that this can return is length of first, + 1 for the comma, + length of string England = 24, so sec is set to be length 24, so that it can fully cover anything the substr()+,+England can return.

 

Solution, always set lengths yourself, don't let the software try to guess for you.

 

Astounding
PROC Star

The key to understanding why is to simplify the problem:

 

sec = substr(first, 1, 7);

 

Here, the length of SEC is 16, the same as the length of FIRST.  The reason:  the third parameter to SUBSTR does not have to be hard-coded.  It can be an expression, calculated based on variables within the incoming data.  So when SAS sees SUBSTR, it doesn't even look at the third parameter.  Rather, it notes that it is taking some portion of FIRST.  It might be taking the whole thing.  So to be safe, SAS assigns SEC the same length as FIRST.

 

When you add ", England" you just have to add that many characters to the length of FIRST.

Kurt_Bremser
Super User

@sanyam13 wrote:

 

can you plz explain how come the length of variable sec is 25 ? 

 

data test;
first = 'ipswich, england';
sec = substr(first,1,7)!!','!!'England';
run;


SAS makes guesses about the required length for a new variable, depending on the length of variables and literals used. To prevent such guesses from happening (as they usually don't end up with the desired result), it is best practice to use the length statement.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 924 views
  • 2 likes
  • 4 in conversation