Re: accessing object variables from callback function
- From: "kaisung@xxxxxxxxx" <kaisung@xxxxxxxxx>
- Date: 29 Jun 2006 23:01:10 -0700
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-----
.
- Follow-Ups:
- Re: accessing object variables from callback function
- From: Dr.Ruud
- Re: accessing object variables from callback function
- References:
- accessing object variables from callback function
- From: kaisung@xxxxxxxxx
- Re: accessing object variables from callback function
- From: anno4000
- Re: accessing object variables from callback function
- From: Brian McCauley
- accessing object variables from callback function
- Prev by Date: Re: test value
- Next by Date: Re: WIN32 PPM and perldoc problems
- Previous by thread: Re: accessing object variables from callback function
- Next by thread: Re: accessing object variables from callback function
- Index(es):
Relevant Pages
|
|