Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Regarding STDOUT and indirect object notation for print

by romandas (Pilgrim)
on Dec 29, 2009 at 20:09 UTC ( #814812=perlquestion: print w/replies, xml ) Need Help??
romandas has asked for the wisdom of the Perl Monks concerning the following question:

Not trying to do anything "useful" here, just experimenting with Perl a bit. I read in Intermediate Perl (p. 146) that the print function (as well as many of the built-in operations on filehandles) are actually just using Perl's indirect object notation to call the print method on the filehandle object.

So, I was curious to see whether this worked with the standard filehandles; STDOUT in particular. However:

my $ofh = *STDOUT; $ofh->print("test 1\n");

didn't work. Nor did:

my $ofh = \*STDOUT; $ofh->print("test 2\n");

or even (not that I expected this to):

STDOUT->print("test 3\n");

So, what gives? I checked perlfaq5, IO::Handle, and perldata but didn't see anything that answered my question specifically. Is there something I'm doing wrong or are the STD* filehandles "special" in some way?

Update: Thanks, all!

Replies are listed 'Best First'.
Re: Regarding STDOUT and indirect object notation for print
by gmargo (Hermit) on Dec 29, 2009 at 20:24 UTC

    You probably left out "use IO::Handle;".

    I get the expected output from the following:

    use IO::Handle; STDOUT->print("Hello, World\n"); my $fh = \*STDOUT; $fh->print("Hello, World\n");

      Interesting. It didn't seem necessary. Without it, the error still refers to the IO::Handle package. Any reason why it seems to "know" to refer to IO::Handle, yet requires the explicit 'use IO::Handle;' statement?

      According to Intermediate Perl, IO::Handle is being used behind the scenes anyway.. so why the explicit statement? "Just cause"? :)

        A blessed object contains the name of the class, in this case IO::Handle. So the program knows the object's class from the object itself, not by reading the IO::Handle file. To find the object's methods, it must be told where to look.

Re: Regarding STDOUT and indirect object notation for print
by Khen1950fx (Canon) on Dec 29, 2009 at 21:43 UTC
    Add diagnostics to the script:
    #!/usr/bin/perl use strict; use warnings; use diagnostics; my $fh = \*STDOUT; $fh->print("Hello, World\n");
    See perlobj for more info.

    Update: removed begin block---not useful here:)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://814812]
Approved by sweetblood
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2018-07-19 16:06 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (411 votes). Check out past polls.