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

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:)