3

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 ?

Miller
  • 34,962
  • 4
  • 39
  • 60
Fred Sullet
  • 371
  • 1
  • 6
  • 18
  • This stinks. DATA can only be read once (unless you note the initial file position and seek back). Why not have an accessor that – ikegami Sep 08 '14 at 03:55

1 Answers1

3

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;
}
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • @user1474829 The preferred way of saying 'thanks' is by accepting the most helpful answer (click on the green checkmark) to any question you ask (which also increases a bit your reputation too), and by up-voting helpful answers (if you have 15+ reputation). Please read the [tour], and good luck with the answers. – clt60 Sep 07 '14 at 14:38
  • Sorry I never really went through all this marking process. Your answer is marked now ! Thanks again – Fred Sullet Sep 07 '14 at 15:10
  • @user1474829: Thank you; I'm pleased I could help you. (Note that the comment above yours wasn't from me but from @jm666) – Borodin Sep 10 '14 at 22:28