At some point, if you use perl enough, you’ll encounter the following error message:
Use of uninitialized value in concatenation (.) or string at ./progname.pl line #.
While it does not stop the program from running, it is kind of annoying at it makes it harder to troubleshoot. This is particularly hard to troubleshoot when it happens a lot, or if it’s happening within other functions.
In some cases, you might not care that the value is empty, so you’d rather not have these errors show up all the time. I use this simple function which converts undefined values to an empty string a lot to avoid this problem:
sub safe { return defined $_[0]?$_[0]:""; }
This is really simple, and therefore won’t slow your code down by having it there. This function uses the ternary operator, so if that’s not familiar to you, then you owe it to yourself to understand it better.
So, this can be used in the following manner:
#!/usr/local/bin/perl -w use strict; my $first="primero"; my $last; print "unsafe!n"; print "first: $firstn"; print "last: $lastn"; #this line generates the error print "n"; print "safe!n"; print "first: ".safe($first)."n"; print "last: ".safe($last)."n"; # this line does not generate the error exit 0; sub safe { return defined $_[0]?$_[0]:""; }
The safe() function can be used when calling other functions (not just printing) that generate a concatenation error as well.
Similarly, you might prefer to print something more explicit like ‘N/A’ instead, when there is no value. You can use something like this:
sub notNA { return defined $_[0]?$_[0]:"N/A"; }
Click here to see all my posts on perl.