variables.cpp

Go to the documentation of this file.
00001 
00003 #include "variables.hpp"
00004 
00005 variable_map global_variables;
00006 
00015 std::string get_value(std::string const& name, variable_map const* local_variables)
00016 {
00017    if (local_variables != 0)
00018    {
00019       variable_map::const_iterator iter(local_variables->find(name));
00020       if (iter != local_variables->end())
00021          return iter->second;
00022    }
00023    return global_variables[name];
00024 }
00025 
00026 std::string expand(std::string str, variable_map const* local_variables)
00027 {
00028    std::string::size_type start(0); // start searching here
00029    while (true)
00030    {
00031       // Find a dollar sign.
00032       std::string::size_type pos(str.find('$', start));
00033       if (pos == std::string::npos)
00034          // No more dollar signs.
00035          return str;
00036       if (pos == str.size() - 1 or str[pos + 1] != '(')
00037          // Not a variable reference.
00038          // Skip the dollar sign, and keep searching.
00039          start = pos + 1;
00040       else
00041       {
00042          std::string::size_type end(str.find(')', pos));
00043          if (end == std::string::npos)
00044             // No closing parenthesis.
00045             return str;
00046          // Get the variable name.
00047          std::string varname(str.substr(pos + 2, end - pos - 2));
00048          // Replace the entire variable reference.
00049          std::string value(get_value(varname, local_variables));
00050          str.replace(pos, end - pos + 1, value);
00051          // Scan the replacement text for more variables.
00052          start = pos;
00053       }
00054    }
00055 }

Generated on Sun Nov 30 09:53:23 2008 for Exploring C++ - Final Forms of Key Examples by  doxygen 1.5.3