beginners:

After RTFM, STFW, etc., I realized that print() was issuing a warning and continuing.


I came up with two solutions:

1.  perldoc -f print() states "Returns true if successful".  So:

        print $s @_ or die $!;

The downside is that the warning still gets printed:

        print() on unopened filehandle NOSUCH at trap-print-errors2.pl line 12.

And $! isn't very meaningful:

        trapped error Bad file descriptor at trap-print-errors2.pl line 12.

2. The warnings pragmatic module has an option for turning warnings into errors:

        use warnings FATAL => 'all';
        print $s @_;

This eliminates the warning message and gives me a meaningful $@:

trapped error print() on unopened filehandle NOSUCH at trap-print-errors2.pl line 24.

Much better!  :-)


HTH,

David



2011-01-16 15:47:28 dpchrist@p43400e ~/sandbox
$ cat trap-print-errors2.pl
#!/usr/bin/perl
use strict;
use warnings;
$| = 1;

sub myprint($@)
{
    my $s = shift;
    eval {
        ###  circumvent Can't use string ("*STDOUT") as a symbol ref...
        no strict 'refs';
        print $s @_ or die $!;
    };
    print "trapped error $@" if $@;
}

sub myprint2($@)
{
    my $s = shift;
    eval {
        ###  circumvent Can't use string ("*STDOUT") as a symbol ref...
        no strict 'refs';
        use warnings FATAL => 'all';
        print $s @_;
    };
    print "trapped error $@" if $@;
}

myprint  '*STDOUT', "hello, world!\n";
myprint2 '*STDOUT', "hello, world!\n";
myprint  '*NOSUCH', "goodbye, cruel world!";
myprint2 '*NOSUCH', "goodbye, cruel world!";
print "all done\n";

2011-01-16 15:48:02 dpchrist@p43400e ~/sandbox
$ perl -c trap-print-errors2.pl
trap-print-errors2.pl syntax OK

2011-01-16 15:48:09 dpchrist@p43400e ~/sandbox
$ perl trap-print-errors2.pl
hello, world!
hello, world!
print() on unopened filehandle NOSUCH at trap-print-errors2.pl line 12.
trapped error Bad file descriptor at trap-print-errors2.pl line 12.
trapped error print() on unopened filehandle NOSUCH at trap-print-errors2.pl line 24.
all done

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to