Well similer to some of the others you might do one of the below, depending if you like map or foreach or subs.

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:

my $var=func($param) || 0;
You might not want to do this if func() returns strings because "" would turn into 0, but in some situations its an acceptable approach.

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.

my ($x,$y); $x=$x+1; # throws warning $y+=1; # no warning
Anyway here's the snippets, TMTOWTDI!
# 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);
HTH
:-)

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.