develooper Front page | perl.perl5.porters | Postings from December 2021

Re: Pre-RFC: `unknown` versus `undef`

Thread Previous | Thread Next
From:
Ovid via perl5-porters
Date:
December 19, 2021 12:13
Subject:
Re: Pre-RFC: `unknown` versus `undef`
Message ID:
11323325.1953443.1639916014632@mail.yahoo.com
The if/else is actually pretty simple if we step back for a moment. I think the confusion is that we misunderstand what an "else" block means in Perl. Let's consider this:

    if ( $var > 3 ) {
        ...
    }
    else {
        ...
    }

In the above, in the else block, we mentally assume that "$var <= 3" holds. In many statically typed languages, that assumption might hold true.

In Perl, $var might be undef and be evaluated as less than three. However, $var might be the string "Hello, World". $var might also be a reference to a hash, we get absolutely no warning, and we hit our else block with an assumption that is probably true ($var <= 3), but not in this particular case. We _should_ be verifying what kind of data that $var holds, but usually we don't. 

Thus, in a dynamic language like Perl, barring validating our data up front, the else block very often makes no guarantees about what kinds of data that we have. Thus, we have this (pseudo-code):

    if I can verify some condition:
        # take some action
    else:
        # condition not verified

An else block in Perl tends not to be the negation of the previous "if" so much as a "catch" for unverified conditions.

Following the principle of least surprise, an unknown value would hit the else branch in the above code because it matches the semantics of Perl. We didn't have guarantees before, we don't have guarantees now, but if they try to do something with that unknown value, they currently get plenty of warnings.

Side note: for the ultra-paranoid, I allow "use Unknown::Values 'fatal';" which tries to make any use of unknown values (aside from testing if they're unknown) a fatal error. So you need to do this to be safe:

    my @filtered = grep { !is_unknown $_ && $_ > 3 } @list;

If unknown values had their own warnings category:

    use feature 'unknown';
    use warnings FATAL => 'unknown';

Devs could opt-in to the strictness they want.

Also, I would kill to be able to write a class and have attributes/slots/fields, whatever, default to `unknown` instead of `undef`. The "is this slot initialized" problem sorta goes away.

Best,
Ovid
-- 
IT consulting, training, specializing in Perl, databases, and agile development
http://www.allaroundtheworld.fr/. 

Buy my book! - http://bit.ly/beginning_perl

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About