问题
I have a super class called Response :
package Response;
use strict;
use warnings;
use HTML::Template;
sub response {
my ( $class, $request ) = @_;
return $request->new_response( $class->status, $class->headers, $class->body );
}
sub body {
my $class = shift;
my $template = HTML::Template->new( 'filehandle' => eval("$class::DATA") );
return $template->output() . $class;
}
sub status {
return 200;
}
sub headers {
return [ 'Content-Type' => 'text/html' ];
}
1;
__DATA__
Default content
and a subclass called URIError :
package URIError;
use strict;
use warnings;
use Response;
our @ISA = qw(Response);
1;
__DATA__
Invalid URI
When URIError->response is called, line
my $template = HTML::Template->new( 'filehandle' => eval("$class::DATA") );
in Response class does not takes DATA section content from URIError class.
What's the syntax to achieve this ?
回答1:
Your code will work if you change the body
method like this. There is no need for eval
: all you have to do is disable strict 'refs'
and dereference the string "${class}::DATA"
sub body {
my $class = shift;
my $data_fh = do {
no strict 'refs';
*{"${class}::DATA"};
};
my $template = HTML::Template->new( filehandle => $data_fh );
$template->output . $class;
}
来源:https://stackoverflow.com/questions/25710301/accessing-data-from-super-class