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

Is there a way to define a sub that writes simultaneously to multiple file handles and has otherwise the same syntax as print?
print STDERR LOGFILE "something bad happened!";
preferably, it would even overload the print function itself.

related---how is the "die" function prototyped?

/iaw

Replies are listed 'Best First'.
Re: prototypes for dual-file handle print?
by ikegami (Patriarch) on Jul 05, 2010 at 18:35 UTC

    There's no way to define a sub to have the same syntax as print, much less a version with an extra handle.

    It is possible to create a handle that writes to two other handles, though. See IO::Tee

    how is the "die" function prototyped?

    Use prototype to determine that.

    $ perl -wle'print prototype("CORE::die")' @

    But also see $SIG{__DIE__} in perlvar.

      There's no way to define a sub to have the same syntax as print

      I always thought function $foo $bar is another notation for $foo->function($bar) (which is also often used to imitate the new operator from other languages). So for example the following works:

      use warnings; use strict; my $mp = MyPrint->new(*STDERR); $mp->myprint("foobar\n"); myprint $mp "foobar\n"; package MyPrint; sub new { my ($class, $out) = @_; return bless { out => $out }, $class; } sub myprint { my ($self, $text) = @_; my $out = $self->{out}; print $out $text; }

      I don't really know why STDERR->print "foobar" doesn't work though. It dies with

      Can't locate object method "print" via package "IO::Handle"
      although the documentation says something else.

        I always thought function $foo $bar is another notation for $foo->function($bar)

        Ah yes. Indirect method call. It can cause headaches, so I don't use it. If a function or op with the same name as the method exists in the current namespace, it's not parsed as an indirect method call. Since print is an op, print $obj ... will never be an indirect method call, and it can't be used to solve the OP's problem.

        $ perl -le 'use IO::Handle();STDOUT->print( qq{A "use IO::Handle" help +s immensely} );' A "use IO::Handle" helps immensely

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

Re: prototypes for dual-file handle print?
by dbbolton (Initiate) on Jul 07, 2010 at 04:52 UTC
    I would probably do something like this:
    #!/usr/bin/perl use strict; use warnings; use autodie; sub mprint { my $message = shift @_; my @files = @_; for (@files) { print $_ "$message\n"; } } my $text = 'string of text'; open( my $out, ">", "output.txt" ); open( my $log, ">>", "my.log" ); &mprint( $text, $out, $log );