ultranerds has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm trying to figure out a way of working out if a header has already been printed.

The reason I'm trying to do this, is that in some functions - we use them in more than one place (and some of them needs the header printed out, while others don't - depending on what functions were called before it)

Is this even possible?

NB: I'm using CGI.pm, with:

print $IN->header;

TIA

Andy

Replies are listed 'Best First'.
Re: Checking a header is printed already?
by Bloodnok (Vicar) on Oct 06, 2009 at 12:09 UTC
    As AM suggests, re-factoring would not be a bad idea.

    Maybe emulate, but definitely not directly use, the inner workings of CGI by implementing a wrapper sub of your own that conditionally calls CGI::header() i.e. knows whether or not it's already printed a header.

    A user level that continues to overstate my experience :-))
Re: Checking a header is printed already?
by almut (Canon) on Oct 06, 2009 at 11:42 UTC

    You could use a global variable (accessible from every place where you're potentially outputting the header) to keep track of whether it's already been printed:

    unless ($header_printed) { $header_printed = print $IN->header; }
      Oh , CGI,
      #### Method: header # Return a Content-Type: style header # #### 'header' => <<'END_OF_FUNC', sub header { my($self,@p) = self_or_default(@_); my(@header); return "" if $self->{'.header_printed'}++ and $HEADERS_ONCE;
      # Change this to 1 to suppress redundant HTTP headers $HEADERS_ONCE = 0;
      $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
      use CGI qw( -unique_headers );
        Hmmm, utilising & referencing a modules' implementation details ... definitely a bad idea!!

        A user level that continues to overstate my experience :-))
        Hi,

        Thanks for the replies guys.

        From looking at that header() bit in CGI.pm, it looks like CGI.pm already does the checking for me? (maybe that would explain why I'm not seing "Content-Type: text/html" printed several times, where the header is called :)

        Thanks!

        Andy
Re: Checking a header is printed already?
by Anonymous Monk on Oct 06, 2009 at 11:34 UTC
    If you need to know this, it is time to refactor your program, but you can use tell
    perl -le"print tell(STDOUT) for 1 .. 3" 0 3 6
      ...so long as the stream is buffered - from tell: ...on a file handle that has been manipulated by sysread(), syswrite() or sysseek(). Those functions ignore the buffering, while tell() does not.

      A user level that continues to overstate my experience :-))