in reply to converting strings to ints

I'm perfectly willing to explicitly convert the blank strings to 0. Is this the easiest way:

@arr1 = map {$_ eq "" ? 0 : $_} @arr1;

The blank strings are the only strings that cause a problem:

use strict; use warnings; use 5.010; say '1' + '2'; --output:-- 3

Why will perl silently convert non-blank strings to integers, but resist converting a blank string to 0? After all, perl converts a blank string to false in a boolean context. It seems like it would be a natural thing for perl to convert a blank string to 0 in a numeric operation.

Replies are listed 'Best First'.
Re^2: converting strings to ints
by BrowserUk (Patriarch) on Mar 20, 2010 at 14:29 UTC
    Why will perl silently convert non-blank strings to integers, but resist converting a blank string to 0?

    It doesn't resist it. It does exactly that. But, you've asked (via use warnings) to be informed of things that might not be right. Always assuming that '' means 0 in a numeric context, when it could mean an absence of data, would be taking DWIM too far.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: converting strings to ints
by Marshall (Canon) on Mar 20, 2010 at 16:35 UTC
    I'm perfectly willing to explicitly convert the blank strings to 0. Is this the easiest way:
    @arr1 = map {$_ eq "" ? 0 : $_} @arr1;

    a common idiom is: @arr1 = map{$_||0}@arr1;
    this converts undef or "" to 0.