Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Handling Embedded Quotes in Conditional Strings Passed to a Stata Program with if Statement

    I have a question about how to pass an argument that is intended to contain quotes into a program for use in an if statement.

    Code:
    clear
    input str6 gender str2 state zipcode
    "Male" "WA" 12345
    "Female" "VA" 54321
    end
    
    capture program drop test_program
    program define test_program
        args condition
        disp "`condition'"
        if `condition' {
            di "`condition' is true"
        }
        else {
            di "`condition' is false"
        }
    end
    
    test_program "zipcode == 12345"
    test_program "gender == "Male""
    When I run that code, the output is:

    . test_program "zipcode == 12345"
    zipcode == 12345
    zipcode == 12345 is true

    . test_program "gender == "Male""
    gender ==
    invalid syntax
    What I am trying to produce is:

    . test_program "gender == "Male""
    gender == "Male"
    gender == "Male" is true
    I also tried

    . test_program `"gender == "Male""'
    gender == Male"" invalid name
    . test_program "gender == `""'Male`""'"
    gender ==
    invalid syntax
    . test_program `"gender == `""'Male`""''
    gender == `'Male`''
    gender == `'Male`'' is false
    How can I correctly pass and evaluate this string with embedded quotes within the if statement in my Stata program? I'd like to keep the argument in the format var == "value" and not simply pass the intended value only, so that I can modify the if statement clause flexibly (e.g., test_program "zipcode == 12345 | gender == "Male"").

    Thanks for any advice!

  • #2
    You need to use compound double quotes, a Stata feature designed to handle precisely this situation. See -help quotes- for details.

    Code:
    clear
    input str6 gender str2 state zipcode
    "Male" "WA" 12345
    "Female" "VA" 54321
    end
    
    capture program drop test_program
    program define test_program
        args condition
        disp `"`condition'"'
        if `condition' {
            di `"`condition' is true"'
        }
        else {
            di `"`condition' is false"'
        }
    end
    
    test_program `"zipcode == 12345"'
    test_program `"gender == "Male""'
    You cannot nest normally quoted expressions inside normally quoted expressions. How, after, all, would the parser (or anyone else) know whether "A"B"C" is to mean "A" followed by B followed by "C" or whether it represents A followed by "B" followed by C, the whole thing being in quotes? Compound double quotes resolve this problem because the opening quotes are different from the closing quotes.

    Comment


    • #3
      Thank you for the help, very much appreciated!

      Comment

      Working...
      X