in reply to How to avoid warnings in HTML::Template::Pro?
Sometimes when working strings, I use Perl's ||= operator to make sure that some string variable is defined to at least "" (null string). This can also be used to set a null string to some default value! The below code demo's this special ||= operator.
Example:
(a) shows how to avoid undef.
(b) shows a "gottcha" if the string is "0",
you probably won't get the result intended! So you have to decide if "0" is
some reasonable value or not and if so, handle that differently.
(c) shows a case
case where the value of "xyzzy" remains unchanged. Perl is returning the value
of "xyzzy" without evaluating the "" part. This is not a simple "True/False" value. The ||= operator is also very fast.
(d) shows setting the default
"after the fact". Often you set a var to some default value and then override
the default in a subsequent statement. However sometimes (like maybe dealing with
a regex pattern match that fails), it is more convenient to have a syntax that says
"hey if it didn't work, then this is the default string that I wanted" when result was undef or null string.
(e)shows a more complex example, I took this from one of my programs (of
course "var names have been changed to protect the innocent").
I did it this way to simplify the thing that outputs this structure. I could
have chosen not to create a value for {'key2'} but then I'd have to do
something on the output end to figure out that this value didn't exist.
#!/usr/bin/perl -w use strict; my $a = undef; print "a=$a\n"; #warning undef var ! $a ||= ""; # $a = $a || ""; print "a=$a\n"; #no warning "" null string my $b= "0"; #gottcha with string of "0" print "b=$b\n"; $b ||= ""; print "b=$b\n"; #sets b to "" (changes "0" to "") my $c = "xyzzy"; $c ||= ""; print "c=$c\n"; #c still "xyzzy" !! my $d = ""; $d ||= "default"; print "d=$d\n"; #d is "default" my %hash; my $e = ""; $hash{'key1'}{'key2'} = $e ||= "--"; print "$hash{'key1'}{'key2'}\n"; #prints "--" __END__ Output: Use of uninitialized value $a in concatenation (.) or string at C:\TEM +P\scratch.pl line 5. a= a= b=0 b= c=xyzzy d=default --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to avoid warnings in HTML::Template::Pro?
by ganeshk (Monk) on Dec 24, 2009 at 18:20 UTC | |
by Marshall (Canon) on Dec 24, 2009 at 22:08 UTC |