Concatenate quoted macro variables

前端 未结 2 961
无人及你
无人及你 2021-01-06 03:21

I\'m just trying to concatenate two quoted macro variables but there doesn\'t seem to be an easy way.

Say we have:

%LET VAR1=\"This is not the greate         


        
相关标签:
2条回答
  • 2021-01-06 03:45

    I'm going to paraphrase Joe's 'real answer' which is - do not store quotes in the macro variable. Single and double quotes in the macro language are no different to any other character. What you should do is delay introducing the quotes until you actually need them. This will result in much cleaner, more flexible, easier to read, and bug-free code.

    Code:

    Notice I've removed the quotes and to concatenate the strings I'm just listing them one after the other:

    %LET VAR1=This is not the greatest song in the world;
    %LET VAR2=this is just a tribute.;
    %LET TRIBUTE=&VAR1 &VAR2;
    

    Example 1

    No quotes are needed to print out the desired string as we are using a %put statement in this first example - for this reason I left the quotes out:

    %PUT &TRIBUTE;
    

    Output :

    This is not the greatest song in the world this is just a tribute.
    

    Example 2

    Quotes are required because we are now in data-step land:

    data _null_;
      put "&TRIBUTE";
    run;
    

    Output :

    This is not the greatest song in the world this is just a tribute.
    

    Note that both of these examples assume you don't actually want to print the quotes to the screen.

    0 讨论(0)
  • 2021-01-06 03:47

    You can use COMPRESS to do this.

    %LET VAR1="This is not the greatest song in the world";
    %LET VAR2="this is just a tribute.";
    
    
    %let VAR3=%sysfunc(compress(&VAR1,%str(%")));
    %put &=var1 &=var3;
    

    It's a bit tricky to remove quotes, but it works.

    You could also do this in a FCMP function, or a function-style macro; here is one example.

    %macro unquote_string(string=);
    %sysfunc(compress(&string.,%str(%'%")))
    %mend unquote_string;
    
    %let VAR3="%unquote_string(string=&var1.) %unquote_string(string=&var2.)";
    %put &=var3.;
    

    Note you shouldn't use CAT functions to concatenate macro variables. They're just text, so typing one after the other automatically concatenates them.

    However, the real answer to your question of 'Is there a better way', is to not store the quotes in the macro variable. Most of the time you should store the macro variable w/o quotes and use it within quotes when needed. SAS Macros do not respect quotes as anything special - they're just a character in a string - so they don't have a specific tool for dealing with this.

    0 讨论(0)
提交回复
热议问题