use warnings; use strict; use Log::Any qw($log); use Log::Any::Adapter ('File', './debug.log', log_level => 'debug'); sub sprintf_prevent_error { my $format = shift; my @a = @_; # if there isn't a format, log an error message and return an error string # might want to return undef instead, and check $EVmsg for undef before blindly doing anything else with it... unless(defined $format) { $log->debugf("sprintf('%s',%s): format is not defined", $format, \@_); return ""; } # if there aren't any arguments, the array is undefined; log an error message and return an error string # might want to return undef instead, and check $EVmsg for undef before blindly doing anything else with it... unless(@a) { $log->debugf("sprintf('%s',%s): array is empty", $format, \@_); return ""; } # count the number of undefined elements in input array, and log the error message # but _don't_ return; we will sanitize the inputs and continue to create the sprintf my $count = grep {!defined} @a; $log->debugf("sprintf('%s',%s): sanitizing %d undefined values", $format, \@_, $count) if $count; # sanitizes the input: replace any undefined elements with the empty string $_//='' for @a; # return the final sprintf of the sanitized input sprintf $format, @a; } sub sanitize { $log->debugf("sanitize(%s): calling", \@_); unless(@_) { # log and return if there's nothing to sanitize $log->debugf("sanitize(%s): nothing to sanitize", \@_); return; }; my $count = grep {!defined} @_; # count the undefined arguments $log->debugf("sprintf(%s): sanitizing %d undefined values", \@_, $count) if $count; $_//='' for @_; } foreach my $hr ( [qw(a b c)], [d => undef, e => undef, 'f'], [qw(x y z)], [] ) { my @HR = @$hr; my $DIcas_text = @HR ? '%s' . ',%s'x$#HR : 'empty array format'; my $EVmsg = sprintf_prevent_error($DIcas_text, @HR); print "STD OUTPUT> $EVmsg\n"; $EVmsg = sprintf_prevent_error(undef, @HR); print "STD OUTPUT> $EVmsg\n"; sanitize($DIcas_text, @HR); $EVmsg = sprintf($DIcas_text, @HR); }