Definition of a periodic function doesn't work when given as the forcing function of an ODE

I was using the nice function how-to-define-a-periodic-function-from-an-interval-to-play-monotonic-sound which works very well for defining a periodic function.

period=2;
g[t_/;0<=t<=period]:=t ;
g[t_]:=g[Mod[t,period]];
Plot[g[t],{t,0,3 period}]


But when I tried to use it as the forcing function of an ODE, Mathematica does not like it

 ode= x''[t]+2 x[t]==  g[t]


The question is, why the above function definition does not work as shown above? And how to make it work? I need to define a period function as RHS of an ODE when I saw this definition given. I do not understand where the Hold is coming from. Am I doing something wrong?

Mathematica 11.2 on windows 7

• Fwiw your recursive g exhibits the same behavior when evaluated standalone. Evaluating g[t] by itself gets the recursionlimit warnings, while g[1] works fine. Being in a differential equation is not the issue. Commented Nov 9, 2017 at 6:31

Why not define g? directly in terms of Mod? Then there will be no problem with recursive calls.

period = 2;
Clear[g]
h[t_] := t/(1 + t^2)
g[t_] = h[Mod[t, period]];
Plot[g[t], {t, 0, 3 period}]


Clear[x]
ode = x''[t] + 2 x[t] == g[t];
x = NDSolveValue[{ode, x[0] == 1.25, x'[0] == 1}, x, {t, 0, 3 period}];
Plot[x[t], {t, 0, 3 period}]


Since g[t] in general is defined recursively (without limit even, since Mod[t,period] does not actually guarantee that 0<=Mod[t,period]<=t and the simplifications and assumptions that would allow that aren't likely to be called during the associated evaluation).

I suspect that if you're using NDSolve changing the second definition of g[t] to g[t_?NumericQ] will make it work fine. If you are intending to solve symbolically, then I would recommending substituting in Mod[t,period] for t in the first definition.