vol7ron
vol7ron

Reputation: 42109

Perl: How to check if CGI::header has already been called?

Using CGI::Carp, I would like to use set_die_handler to gracefully output an error message.

The web page is not expected to encounter an error, but if it does and it occurs somewhere after print header has already been called, it outputs the header as text and the page will most likely be formatted incorrectly.

As the question states, I would like to check if CGI::header() has already been called. This could be done by using a global variable and setting it every place I may have the function being called, but I am hoping this might already be performed internally; or there might be a way to parse what has already been sent to STDOUT. An example of non-working code:

BEGIN {
   set_die_handler(
       sub {
           print header if not CGI::header_called;
           # or possibly,something like: if (<STDOUT> !~ /Content\-Type/)
           ...
       });
}

Note:
Comments related to age of CGI.pm are accepted, but are also quickly dismissed :) It's realized that Perl has MVC frameworks

Upvotes: 2

Views: 527

Answers (2)

Dave Cross
Dave Cross

Reputation: 69294

CGI.pm keeps track of this information in an attribute called .header_printed, which you can check if you want. It's worth noting that this is an internal feature and is undocumented, so it's not guaranteed to continue working in future versions.

$ perl -MCGI -E'$c = CGI->new; say $c->header unless $c->{".header_printed"}; say $c->header unless $c->{".header_printed"};'
Content-Type: text/html; charset=ISO-8859-1

Upvotes: 1

ikegami
ikegami

Reputation: 385996

It's not documented, but CGI does keep track of whether header has already been called or not.

>perl -e"use CGI qw( :cgi ); print header; print header;"
Content-Type: text/html; charset=ISO-8859-1

Content-Type: text/html; charset=ISO-8859-1


>perl -e"use CGI qw( :cgi -unique_headers ); print header; print header;"
Content-Type: text/html; charset=ISO-8859-1


>

Upvotes: 10

Related Questions