Accessing __DATA__ from super class
Asked Answered
M

1

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 ?

Melanymelaphyre answered 7/9, 2014 at 12:42 Comment(1)
This stinks. DATA can only be read once (unless you note the initial file position and seek back). Why not have an accessor thatPolyclinic
A
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;
}
Ataliah answered 7/9, 2014 at 14:23 Comment(3)
@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.Kremenchug
Sorry I never really went through all this marking process. Your answer is marked now ! Thanks againMelanymelaphyre
@user1474829: Thank you; I'm pleased I could help you. (Note that the comment above yours wasn't from me but from @jm666)Ataliah

© 2022 - 2024 — McMap. All rights reserved.