Links: Next Previous Up Top

# What about the handler argument?

The second argument to the `sgml` subroutine is the actual code or data associated with each event. If it is a string, it will be printed literally using the `output` subroutine from the `SGMLS::Output` library; if it is a reference to a `perl5` subroutine, the subroutine will be called whenever the event occurs. The following three `sgml` commands will have identical results:

    # Example 1
    sgml('<DOC>', "\\begin{document}\n");

    # Example 2
    sgml('<DOC>', sub {
      output "\\begin{document}\n";
    });

    # Example 3
    sub do_begin_document { output "\\begin{document}\n"; }
    sgml('<DOC>', \&do_begin_document);

For simply printing a string, of course, it does not make sense to use a subroutine; however, the subroutines can be useful when you need to check the value of an attribute, perform different actions in different contexts, or perform other types of relatively more complicated post-processing.

If your handler is a subroutine, then it will receive two arguments: the `SGMLS.pm` event's data, and the `SGMLS.pm` event itself (see the `SGMLS.pm` documentation for a description of event and data types). The following example will print `'\begin{enumerate}'` if the value of the attribute `TYPE` is `'ORDERED'`, and `'\begin{itemize}'` if the value of the attribute `TYPE` is `'UNORDERED'`:

    sgml('<LIST>', sub {
      my ($element,$event) = @_;
      my $type = $element->attribute('TYPE')->value;

      if ($type eq 'ORDERED') {
        output "\\begin{enumerate}\n";
      } elsif ($type eq 'UNORDERED') {
        output "\\begin{itemize}\n";
      } else {
        die "Bad TYPE '$type' for element LIST at line " .
          $event->line . " in " . $event->file . "\n";
      }
    });

You will not always need to use the event argument, but it can be useful if you want to report line numbers or file names for errors (presuming that you called `sgmls` or `nsgmls` with the -l option). If you have a new version of `nsgmls` which accepts the -h option, you can also use the event argument to look up arbitrary entities declared by the program. See the SGMLS_Event documentation for more information.

Links: Next Previous Up Top