Announcement

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

  • macro problem

    Not sure why global "year" is not working in log using command

    global project "c:\work\education"
    global year 2018
    log using "$project\log\dist_$year_edu1.log",replace



    . log using "$project\log\dist_$year_edu1.log",replace
    (note: file c:\work\education\log\dist_.log not found)
    file c:\work\education\log\dist_.log could not be opened
    r(603);

  • #2
    Well, something complicated happens when you have global de-referencing preceded by an underscore (_) character following another global. I don't actually understand why. Look at these examples:

    Code:
    . global first ABC
    
    . global second DEF
    
    . display "$second$first"
    DEFABC
    
    . display "$second_$first"
    ABC
    
    . display "$second&$first"
    DEF&ABC
    
    . display "_$first"
    _ABC
    Anyway, you probably shouldn't be using global macros to store this information. Global macros are inherently unsafe and their use is a poor programming practice except when there is no alternative available. If you are going to have several levels of nested program or do-file calls all referencing $project and $year, then this may be such an occasion. Even so, I would not use those names because they are too common and the risk of a name clash with somebody else who has used a global with the same name is too high. But if these are only being used in the current file, or perhaps passed only down one level, then it is far better to use local macros for this purpose.

    Comment


    • #3
      When interpreting
      Code:
      $project\log\dist_$year_edu1.log
      Stata believes there is a global variable
      Code:
      $year_edu1
      which of course is not defined, which is why nothing is substituted for that global variable. Try instead
      Code:
      $project\log\dist_${year}_edu1.log
      Added in edit: In post #2, $second_ is a legitimate global variable name that is not defined, all the other examples work as one would expect.
      Last edited by William Lisowski; 12 Feb 2018, 14:08.

      Comment


      • #4
        Thanks for the explanation in #3.

        Yet another bonus from local macros is that because they are referenced by surrounding them in paired delimiters, instead of just preceding them by $, you do not run into these ambiguities about what is intended to be part of the macro name and what isn't. The names of local macros have explicit beginnings and endings.

        Comment


        • #5
          Sorry for being late to thank you both, Lisowski and Schechter, for your helpful comments. I helped to solve my problem.

          Comment

          Working...
          X