Accessing __DATA__ from super class

别来无恙 提交于 2019-12-10 19:03:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!