Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

check if a filehandle is STDOUT when using use strict;

by ISAI student (Scribe)
on Dec 31, 2012 at 10:03 UTC ( #1011032=perlquestion: print w/ replies, xml ) Need Help??
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?

Comment on check if a filehandle is STDOUT when using use strict;
Select or Download Code
Re: check if a filehandle is STDOUT when using use strict;
by zwon (Monsignor) 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 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 mhearse (Hermit) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1011032]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2014-07-22 09:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (109 votes), past polls