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

In a discussion about non-buffered output and browser timeouts someone at work said:

  "'$|++' is nasty. Set it to 1, don't rely on it not being -1."

That seems logical enough in a 'better safe than sorry' sort of way, but, out of interest, are there any situations where a CGI script would start out with $| being -1 and what are they?

Edit: chipmunk 2001-06-01

Replies are listed 'Best First'.
Re: $ != 0 at start of script
by runrig (Abbot) on Jun 01, 2001 at 20:41 UTC
    $| is a magic variable and can only be 0 or 1.
    $|=0; print $|; $|=-1; print $|; $|++; print $|; $|++; print $|; prints: 0 1 1 1
Re: $ = 0 at start of script
by japhy (Canon) on Jun 01, 2001 at 21:11 UTC
    $| can never be -1, unless someone has tied it to some class, or has set it via a typeglob:
    tie $|, 'Pkg', ...; # or *| = *foo; $foo = 100; print $|; # 100!
    But those are really esoteric cases; and if you're really panicky, just say $| = 0 or $| = 1.

    For those interested, $| is as good as a boolean:

    /* in sv.h */ #define IOf_FLUSH 4 /* in mg.c -- the magic file */ /* in Perl_magic_get() */ case '|': sv_setiv(sv, (IV)(IoFLAGS(GvIOp(PL_defoutgv)) & IOf_FLUSH) != 0 ); break; /* in Perl_magic_set() */ case '|': { IO *io = GvIOp(PL_defoutgv); if ((SvIOK(sv) ? SvIVX(sv) : sv_2iv(sv)) == 0) IoFLAGS(io) &= ~IOf_FLUSH; else { if (!(IoFLAGS(io) & IOf_FLUSH)) { PerlIO *ofp = IoOFP(io); if (ofp) (void)PerlIO_flush(ofp); IoFLAGS(io) |= IOf_FLUSH; } } } break;
    Perl_magic_get() ends up returning a 0 or a 1 (which is what you get when you fetch the value of $|). Perl_magic_set() determines whether the value you're setting $| to is true or false, and sets or unsets the IOf_FLUSH bit accordingly.

    japhy -- Perl and Regex Hacker
Re: $= 0 at start of script
by petral (Curate) on Jun 03, 2001 at 19:44 UTC
    > perl -lwe 'print $|-- for 0..5' 0 1 0 1 0 1
      p