next up previous contents
Next: Writing Subroutines to Translate Up: Writing Subroutines to Translate Previous: Commands with arguments   Contents


Optional arguments

Suppose you want the \monthname command defined in the previous section to have an optional argument instead of a mandatory argument. If the argument is omitted, the current month will be used. The LaTeX code will now look like:

\newcommand{\monthname}[1][\month]{%
\ifcase#1
\or January%
\or February%
\or March%
\or April%
\or May%
\or June%
\or July%
\or August%
\or September%
\or October%
\or November%
\or December%
\fi}
The Perl subroutine &do_cmd_monthname will now need to use the subroutine &get_next_optional_argumentname=&get_next_optional_argument,sort=getnextoptionalargument,description=Extracts optional argument at the start of $_ and returns ($argument, $pattern).&get_next_optional_argument. This returns two parameters: the contents of the optional argument and the pattern. For example, if $_ contains the string
[1] is a very chilly month
in Britain.
then
($month,$pat) = &get_next_optional_argument;
will result in $month="1" and $pat="[1]", and $_ will now contain the string:
is a very chilly month
in Britain.
The subroutine &do_cmd_monthname can now be modified as follows:
sub do_cmd_monthname{
   local($_) = @_;
   local($sec,$min,$hr,$day,$month,$pat);
                                                          
   ($month,$pat) = &get_next_optional_argument;
                                                          
   if ($month eq '')
   {
      ($sec,$min,$hr,$day,$month) = localtime(time);
      $month++;
   }
                                                          
   $Month[$month] . $_;
}
Note: be careful not to do:
$month = &get_next_optional_argument;



Dr Nicola L C Talbot 2005-06-10