I have a scenario where I'm testing for a condition within a group which will then trigger inputting a corresponding outside file. The problem is that the outside file may contain control sequences that I later need. I tried to make sure the expansion was going to happen after closing the group as in the following example. (I've omitted the testing condition because this example nevertheless duplicates my error.)
\begin{filecontents}{anotherfile}
\def\aemoon{This is the moon}
This is my other file.
\end{filecontents}
\documentclass{article}
\begin{document}
Testing
\begingroup
\def\helloworld{\input{anotherfile}}
\expandafter\helloworld
\endgroup
\aemoon
\end{document}
But this results in an error
! Undefined control sequence.
l.17 \aemoon
The same thing happens below where there's no need to input an outside file
\documentclass{article}
\begin{document}
Testing
\begingroup
\def\helloworld{\newcommand\aemoon{this is the moon}}
\expandafter\helloworld
\endgroup
\aemoon
\end{document}
In either example, I was expecting that the command \aemoon was getting defined outside of the group on account of \expandafter. (\aftergroup will clearly not work since after the group \helloworld has not been defined.)
Thinking back to my original situation where I'm inputting another file, I know I could write something like
\begin{filecontents}{anotherfile}
\def\aemoon{This is the moon}
This is my other file.
\end{filecontents}
\documentclass{article}
\begin{document}
Testing
\begingroup
\gdef\helloworld{\input{anotherfile}}
\endgroup
\helloworld
\aemoon
\end{document}
So, I do have a work around. But I would like to know why the first two examples are not working because my understanding is that the expansion should be happening outside the group, but...
So, what is happening here?
\helloworldand then the group ends, destroying all assignments made inside it. So, if you say\begingroup\ifbla\def\foo{bla}\else\def\foo{bar}\fi\def\gnu{A \foo}\expandafter\endgroup\gnuyou'll be in trouble. – egreg Jan 08 '16 at 22:08