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

What are all the differences (or is it a prank and there aren't any?) between:
$|=1;
and
select((select(STDOUT), $|=1)[0]);

Replies are listed 'Best First'.
Re: Unbuffered Output...
by Aristotle (Chancellor) on Feb 21, 2005 at 04:56 UTC

    select returns the previously selected filehandle. So this bit:

    ( select( STDOUT ), $|=1 )

    builds a two-element list where the first element contains the previously selected filehandle, and the second element is $|. Note that because the elements are evaluated in order, select( STDOUT ) has taken effect before $|=1 so that autoflush is set for STDOUT.

    Now, we pick the first element from this list:

    ( select( STDOUT ), $|=1 )[ 0 ]

    that is, the previously selected filehandle. This is passed to another select:

    select( ( select( STDOUT ), $|=1 )[ 0 ] );

    which means the filehandle that was selected before selecting STDOUT is re-selected. So what this ditty does is set autoflush on STDOUT without affecting which filehandle is currently selected while avoiding any temporary variables. It's a very neat, idiomatic bit of Perl.

    Makeshifts last the longest.

Re: Unbuffered Output...
by chas (Priest) on Feb 21, 2005 at 03:48 UTC
    $|=1; sets autoflush on the current default output, while select((select(STDOUT), $|=1)[0]); starts with some default output, then selects STDOUT as the default output and sets autoflush there, then selects the original starting default output. These are certainly different (especially when the starting default output isn't STDOUT.)
    chas