Re: accessing object variables from callback function



Thanks for the tip on closures, that's what I was looking for. For
completeness, here's what my final program looks like.

-Kai


-----BEGIN MyTest.pm-----
#################################
# A simple class that loads an
# XML file and returns the number
# of tags in the file.
#################################
package MyTest;

use XML::Parser;

# Create a new object
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = { @_ };
bless($self, $class);
return $self;
}

# Load an xml file and count the number of tags
sub load {
my $self = shift;
my $file = shift;
my $parser = XML::Parser->new(ErrorContext => 2);
$parser->setHandlers(Start => sub { $self->_start_handler(@_); });
$parser->parsefile($file);
}

# Return the number of tags in loaded xml file
sub numTags {
my $self = shift;
return $self->{numTags};
}

# Private method
sub _start_handler {
my $self = shift;
my $p = shift;
$self->{numTags}++;
}
1;
-----END MyTest.pm-----

-----BEGIN mytest.pl-----
#!/usr/bin/perl -w

use MyTest;

my $test = MyTest->new();

$test->load("test.html");
print "numTags = " . $test->numTags() . "\n";
-----END mytest.pl-----

.



Relevant Pages

  • Re: XML::LibXML navigation
    ... I have to do some sanity checks on a large xml file of addresses (snip ... I am struggling to navigate around a record. ... # find the tags and print ... address => sub { ...
    (perl.beginners)
  • XML - Parsing
    ... end tags in an XML file in perl. ... sub StartTag { ... I am not sure how to read "Marriott" in perl. ...
    (comp.lang.perl.misc)
  • sitemap generator for Perl
    ... I want to run the sitemap generator ... Returns the minimum number of links to traverse from the root URL of ... my $class = shift; ...
    (perl.beginners)
  • Re: How can I create instantiable objects (not classes)?
    ... a child object inherits not only its parent object's ... sub fee { ... my $class = shift; ... For example, an object of type Car might receive a message named "ticket," and since a car does not know what to do with a ticket, it would pass that message to an object of type Driver. ...
    (comp.lang.perl.misc)
  • Re: Packages and returning errors
    ... > array intact. ... sub is_a_instance_method { ... my $class = shift; ... You need to fix the scope of $error by moving its declaration outside ...
    (comp.lang.perl.misc)