Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2022-05-28 18:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (100 votes). Check out past polls.

    Notices?