Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: "Safe" print?

by pemungkah (Priest)
on May 15, 2013 at 03:31 UTC ( #1033600=note: print w/replies, xml ) Need Help??

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?

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1033600]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2023-03-22 18:47 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (60 votes). Check out past polls.