http://qs1969.pair.com?node_id=1011032

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

Hello all. I am rewriting a subroutine, in which a check if a filehandle is in fact STDOUT is performed.

When not using  use strict, the answer is very simple. However, bare word is anallowed when  use strict is applied . Would  ( $bar == \*STDOUT ) do?

Replies are listed 'Best First'.
Re: check if a filehandle is STDOUT when using use strict;
by bart (Canon) on Dec 31, 2012 at 11:22 UTC
    I seriously doubt if comparing to \*STDOUT will do. After all, a filehandle is a special entry in a typeglob, it's not just a plain scalar that you can compare. It's not even a reference.

    But you can always use fileno, and applying the snippet of code on the page, you can do:

    if(fileno($fh)==fileno(STDOUT)) { # ... }

    And yes, fileno(STDOUT) is allowed by strict.

    There could be a bit of a problem if $fh is a tied filehandle instead of a physical handle. In that case, fileno will return -1, which is different from the default value for STDOUT, which is 1. If you tie STDOUT too, then you're in trouble.

      It's a physical handle. Thanks!
Re: check if a filehandle is STDOUT when using use strict;
by zwon (Abbot) on Dec 31, 2012 at 10:39 UTC

    It depends on what do you mean by filehandle is in fact STDOUT. E.g. consider the following:

    $ perl -E'open my $foo, "<&=1"; say $foo->fileno; say $foo == \*STDOUT + ? "STDOUT" : "Not STDOUT"' 1 Not STDOUT
      I can assume that it gets assigned the value of \*STDOUT I.E. $file= \*STDOUT ;
Re: check if a filehandle is STDOUT when using use strict;
by mhearse (Chaplain) on Jan 01, 2013 at 17:58 UTC
    #!/usr/bin/env perl use strict; print "PID: " . $$, "\n"; open STDOUT, ">/tmp/returntozork" or die $!; while (1) { sleep 10; }
    PID: 3868 shell> ls -l /proc/3868/fd/ lrwx------. 64 Jan 1 09:55 2 -> /dev/pts/0 l-wx------. 64 Jan 1 09:55 1 -> /tmp/returntozork lrwx------. 64 Jan 1 09:55 0 -> /dev/pts/0