# Define macro based on Datatool contents

I can define a macro of the form \csname../dirX Color\endcsname manually and use it as desired. However, I am unable to do the same thing based on the contents as read by the datatool package.

The MWE as below yields:

The desired output of the last line (after uncommenting) is:

## Code:

\documentclass{article}
\usepackage{datatool,xstring,xcolor}

\usepackage{filecontents}
\begin{filecontents*}{MyData.csv}
Directory, Color
../dirB,    red
../dirC,    yellow
\end{filecontents*}

\begin{document}
\textbf{Without datatool:}
\expandafter\gdef\csname../dirA Color\endcsname{blue}%
\xdef\DirAColor{\csname../dirA Color\endcsname}
Color for '../dirA' is '\DirAColor': \textcolor{\DirAColor}{../dirA}.

\bigskip
\textbf{With datatool}

\DTLdisplaydb{MyDB}
\medskip
\DTLforeach{MyDB}{\Dir=Directory,\DirColor=Color}{%
\edef\ExpandedDirColor{\DirColor}
\expandafter\gdef\csname\Dir Color\endcsname{\ExpandedDirColor}%
}

\xdef\DirBColor{\csname../dirB Color\endcsname}

Color for '../dirB' is '\DirBColor':% \textcolor{\DirBColor}{../dirB}.
\end{document}
-
I think you're simply missing a space here: \csname\Dir Color\endcsname. So either use \csname\Dir\space Color\endcsname or \xdef\DirBColor{\csname../dirBColor\endcsname}. –  Stephan Lehmke Jan 8 '13 at 3:49
@StephanLehmke: Hmmm. That was easy.. Please post as answer. –  Peter Grill Jan 8 '13 at 4:06

\csname is a useful construct for defining a "dynamic" macro name based on some input, but when you're using the same basic structure in different places, you have to make sure the constructed macro names really match up.

For instance, comparing this

\expandafter\gdef\csname\Dir Color\endcsname{\ExpandedDirColor}%

with that

\xdef\DirBColor{\csname../dirB Color\endcsname}

note that the second actually contains a space character in the macro name while in the first construct, the apparent space is "eaten" as a delimiter to the macro name \Dir.

To make both constructs match, you should either use

\csname\Dir\space Color\endcsname

or

\xdef\DirBColor{\csname../dirBColor\endcsname}
-
I think the code for the last two lines should be in display mode. Otherwise it is not clear if that there is a space after \space. –  Peter Grill Jan 8 '13 at 5:14
@PeterGrill Ok, edited. –  Stephan Lehmke Jan 8 '13 at 6:13