http://www.perlmonks.org?node_id=1033600


in reply to "Safe" print?

How about this?
sub safe_print { for my $item (@_) { print defined $item ? $item : '[undef]'; } }
Or more condensed:
sub safe_print { local $_; print map { defined $_ ? $_ : '[UNDEF]' } @_; }
You'll need to tweak it if you want to support alternate filehandles. Might be easier as an OO class at that point since you have data and actions bound together. Note this probably could use a few extra tweaks, but it should get you on the right road.
use strict; use warnings; sub new { my($class, $args) = @_; $args = {} unless defined $args; die "Arguments must be a hash ref\n" unless ref($args) eq 'HASH'; my $self = { %$args }; bless $self, $class; return $self; } sub print { my $self = shift; $self->{fh} = *STDOUT unless defined $self->{fh}; my $fh = $self->{fh}; print $fh (map { defined $_ ? $_ : '[UNDEF]' } @_); } 1;
Using it:
open my $fh, ">", "foo" or die "Can't open foo: $!\n"; my $printer = SafePrinter->new({fh => $fh}); $printer->print("so it goes", undef, 'and it went', "\n");
foo contains: so it goesUNDEFand it went </code> Will that do?