Oh, and something to remember on this level '||' returns the last true value evaluated, or if there aren't any the last value evaluated whatever it is, this is useful for applying defaults to variables, or for creating fallbacks in certain situations.
For instance if your array was being populated by a function that returned a numeric value if legal input was provided and undef if not you could convert the undefs nicely to 0 by this:
You might not want to do this if func() returns strings because "" would turn into 0, but in some situations its an acceptable approach.my $var=func($param) || 0;
More useful is that the assignment version of most of the binary operators (+= -= etc) dont throw warnings if the var is undef to start with, even though the binary versions do. So we only get 1 warning from the below, even though on a conceptual level they are identical.
Anyway here's the snippets, TMTOWTDI!my ($x,$y); $x=$x+1; # throws warning $y+=1; # no warning
HTH# heres a functional way my @no_undefs=map{$_ || 0} @has_undefs; # or with a modifier !defined($array[$_]) and $array[$_]=0 foreach 0..$#array; # or more elegantly $array[$_]||=0 foreach 0..$#array; # or with a funky sub # might be slow or big lists though sub undefs2zero {$_[$_]||=0 foreach 0..$#_} undefs2zero(@array);
Yves
--
You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)
In reply to Re: undefined elements in array
by demerphq
in thread undefined elements in array
by Ntav
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |