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

Mighty Monks,

I've been reading through "Network Programming with Perl" and, while working through some of the examples, I ran into a problem using IO::File to redirect standard output (STDOUT). I thought the following code would print "Here's some data\n" to 'test.log':

1 #! /usr/bin/perl 2 3 use strict; 4 use warnings; 5 6 use IO::File; 7 8 my $logfile = 'test.log'; 9 10 STDOUT->open($logfile, '>') or die "Can't re-direct STDOUT:$!"; 11 12 print "Here's some data...\n";

but instead, I get the following error:

Can't locate object method "open" via package "IO::Handle" (perhaps yo +u forgot to load "IO::Handle"?) at ./redirect_stdout line 11. shell returned 255

But the following works on my created filehandle:

1 #! /usr/bin/perl 2 3 use strict; 4 use warnings; 5 6 my $logfile = 'test.log'; 7 my $FH = new IO::File; 8 9 $FH->open($logfile, '>') or die "Can't open $logfile for writing:$!" +; 10 11 $FH->print("Here's some data...\n");

What's going on here?
njcodewarrior

Replies are listed 'Best First'.
Re: Using IO::File to redirect STDOUT
by ikegami (Patriarch) on May 08, 2006 at 01:10 UTC
    As you can see from the error message, STDOUT is a IO::Handle (which doesn't have an open method), not a IO::File (which does). Use open(*STDOUT, '>', $logfile).

      Quoting from the book "Network Programming with Perl" by Lincoln D. Stein (pp 29 - 30):

      'When you load IO::File (technically, when IO::File loads IO::Handle, which it inherits from), it adds methods to ordinary filehandles. This means that any of the methods in IO::File can also be used with STDIN, STDOUT, STDERR or even with any of the conventional filehandles that you happen to create'.

      Is the book incorrect or am I missing something?

      njcodewarrior

        That's wrong.
        "This means that any of the methods in IO::File"
        should read
        "This means that any of the methods in IO::Handle"

        The following are methods IO::File has, but IO::Handle does not:

        • open
        • binmode
        • seek
        • sysseek
        • tell