How to remember a length across compilations
\def\reloadmylen#1{\global\mylen=#1}
\protected@write
is used if one wants to write the current value of a macro at the time of page-shipout to an external file.
In the OP's case, the dimen value after use of \changelen
shall be stored in \@auxout
(\jobname.aux
). This can be done immediately and doesn't need to be delayed further, since the last value written out by \changelen
is what counts when \jobname.aux
is re-read during the second LaTeX run. That is why \protected@write
is not the best choice here, but \immediate\write
should be preferred.
\documentclass{article}
\newlength\mylen
\mylen=0pt% Default value
\makeatletter
% persistently sets length register
\def\changelen#1#2{%
\global#1=#2%
\immediate\write\@auxout{\global#1=\the#1}%
}
\makeatother
\begin{document}
\the\mylen% Prints 20pt after the second run.
\changelen{\mylen}{10pt}
%\changelen{\mylen}{20pt}
\newlength\otherlen\otherlen=20pt
\changelen{\mylen}{\otherlen} % also works (can be used like `\setlength')
\end{document}
Depending on the precision you need, you can simply use the totcount
package:
\documentclass{article}
\usepackage{printlen}
\usepackage{totcount}
\newtotcounter{mylenght}
\begin{document}
\uselengthunit{mm}\printlength{\totvalue{mylenght}}
\newlength\mylen
\setlength{\mylen}{4.9999999mm}
\setcounter{mylenght}{\mylen}
\end{document}