use strict; use warnings; # ABSTRACT: Use 'unknown' values instead of undef ones package Unknown::Values; $Unknown::Values::VERSION = '0.102'; use 5.01000; use Unknown::Values::Instance; use Unknown::Values::Instance::Fatal; use Unknown::Values::Instance::Object; use Carp (); use Scalar::Util 'blessed'; sub import { my $class = shift; my $caller = caller; my $unknown_class = 'Unknown::Values::Instance'; if (@_) { if ( ':FATAL' eq $_[0] ) { $unknown_class = 'Unknown::Values::Instance::Fatal'; } elsif ( ':OBJECT' eq $_[0] ) { $unknown_class = 'Unknown::Values::Instance::Object'; } else { Carp::croak("I don't know how to create an Unknown::Values object of type '$_[0]'"); } } my $unknown = $unknown_class->new; my $unknown_sub = "${caller}::unknown"; my $is_unknown_sub = "${caller}::is_unknown"; no strict 'refs'; *$unknown_sub = sub {$unknown}; *$is_unknown_sub = \&is_unknown; } sub is_unknown(_) { defined $_[0] && blessed( $_[0] ) && ( # Unknown::Values::Instance::Object overrides isa() ( 'Unknown::Values::Instance::Object' eq ref $_[0] ) || $_[0]->isa("Unknown::Values::Instance") ); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Unknown::Values - Use 'unknown' values instead of undef ones =head1 VERSION version 0.102 =head1 SYNOPSIS use Unknown::Values; my $value = unknown; my @array = ( 1, 2, 3, $value, 4, 5 ); my @less = grep { $_ < 4 } @array; # (1,2,3) my @greater = grep { $_ > 3 } @array; # (4,5) my @underpaid; foreach my $employee (@employees) { # this will never return true if salary is "unknown" if ( $employee->salary < $threshold ) { push @underpaid => $employee; } } Or: use Unknown::Values ':FATAL'; my $value = unknown; if ( 3 < $value ) { ... } # fatal error if ( is_unknown $value ) { # not a fatal error ... } Or: # see documentation Unknown::Values::Instance::Object use Unknown::Values ':OBJECT'; # NULL Object pattern my $employee = unknown; if ( $employee->salary < $threshold ) { # we will never get to here } =head1 DESCRIPTION This code is alpha. Some behavior may change. The module name may change. This module provides you with two new keywords, C and C. C is conceptually similar to the SQL C value. From the point of view of logic, this often an improvement over C values. Consider the following code, used to give underpaid employees a pay raise: foreach my $employee (@employees) { if ( $employee->annual_salary < $threshold ) { increase_salary($employee); } } Who got a salary increase? Ordinarily that would be: =over 4 =item * Every employee with a salary less than C<$threshold>. =item * Every employee with an undefined salary. =back Why are we giving salary increases to employees whose salary is undefined? Consider the types of employees who might have undefined annual salaries: =over 4 =item * Unpaid interns =item * Volunteers =item * Hourly employees We don't know in advance how many hours a week they will work. =item * CEO Maybe it's a private company so his salary is confidential. =item * New employee Their salary has not yet been entered in the database. =back If, however, the C<< $employee->salary >> method returns C, the comparison will I return false, thus ensuring that anyone with an unknown salary will not have their salary increased. As another example, consider the following statements: my @numbers = ( 1,2,3,4,unknown,5,6,unknown,7 ); my @less = grep { $_ < 5 } @numbers; # 1,2,3,4 my @greater = grep { $_ > 4 } @numbers; # 5,6,7 In other words, C comparisons return false because we can't know how they compare to other values. Now replace the above with C: my @numbers = ( 1,2,3,4,undef,5,6,undef,7 ); my @less = grep { $_ < 5 } @numbers; # 1,2,3,4,undef,undef my @greater = grep { $_ > 4 } @numbers; # undef,5,6,undef,7 In other words, you're probably getting garbage. =head1 EXPORTS =head2 C my $value = unknown; A safer replacement for C. Conceptually, C behaves very similarly to SQL's C. Note that comparisons will return false, but stringification is always a fatal This ensures that you cannot accidentally use unknown values as hash keys or array indices: my $unknown = Person->fetch($id); print $unknown; # fatal $cache{$unknown} = $id; # fatal $ordered[$unknown] = $id; # fatal =head2 C if ( is_unknown $value ) { ... } Test if a value is C. Do I use C<< $value->isa(...) >> because the class is blessed into is not guaranteed. =head1 FUNCTIONS =head2 C Use C instead of C when you don't want the value to default to false. =head2 C Test whether a given value is C. my $value1 = unknown; my $value2 = undef; my $value3 = 0; my $value4 = 1; if ( is_unknown $value1 ) { ... this is the only one for which this function returns true } Defaults to C<$_>: foreach (@things) { if ( is_unknown ) { # do something } } If you have specified C<< use Unknown::Values ':FATAL' >>, this is the I safe use for C values. Any other use is fatal. =head1 NULL Objects If you're a fan of the NULL object pattern, you can do this: use Unknown::Values ':OBJECT'; my $unknown = unknown; if ( $unknown->foo->bar->baz > $limit ) { # we will never get here } See L for more information. =head1 SORTING C values sort to the end of the list, unless you reverse the sort. my @sorted = sort { $a <=> $b } ( 4, 1, unknown, 5, unknown, unknown, 7 ); eq_or_diff \@sorted, [ 1, 4, 5, 7, unknown, unknown, unknown ], 'Unknown values should sort at the end of the list'; my @sorted = sort { $b <=> $a } ( 4, 1, unknown, 5, unknown, unknown, 7 ); eq_or_diff \@sorted, [ unknown, unknown, unknown, 7, 5, 4, 1 ], '... but the sort to the front in reverse'; This is a bit arbitrary, but some decision had to be made and I thought that you'd rather deal with known values first: my @things = sort @other_things; foreach (@things) { last if is_unknown; # work with known values } Note that if you specify C<< use Unknown::Values 'fatal' >>, sorting an unknown value is fatal. =head1 EQUALITY An C value is equal to nothing becuase we don't know what it's value is (duh). This means that if an employee's salary is unknown, the following will B work: if ( $employee->salary == unknown ) { # eq fails, too ... } Use the C function instead. if ( is_unknown $employee->salary ) { ... } We also assume that inequality fails: if ( 6 != unknown ) { ... always false } if ( 'Ovid' ne unknown ) { ... always false } B: That's actually problematic because an unknown value should be equal to itself but not equal to I unknown values. From the standpoint of pure logic, it's wrong, but it's so awfully convenient that we've allowed it. We might revisit this. Note that if you specify C<< use Unknown::Values 'fatal' >>, testing for equality is fatal. =head1 ILLEGAL OPERATIONS Attempting to use C values in ways that don't make sense is a fatal error (unless you specified C<< use Unknown::Values 'fatal' >>, in which case, using C values in I way other than with C is fatal). my $value1; $value1 += 1; # results in 1 my $value2 = unknown; $value2 += 1; # fatal This is a side-effect of not allowing stuff like this if one of these values is C. my $total = $price * $tax_rate; If you want C<+=> to work, properly initialize the variable to a value: my $value = 0; $value += 1; =head1 BUGS Probably plenty. =head1 WARNING Conditional assignment does not work, but THIS IS NOT A BUG! my $value = unknown; $value ||= 1; # this is a no-op, as is //= $value++; # fatal! This is not a bug because we cannot positively state whether $value is true or defined, thus meaning that C<||=> and C must both return C values. To fix this, either assign a value when you declare the variable: my $value = 1; Or test to see if it's C: $value = 1 if is_unknown $value; =head1 LOGIC We follow Kleene's traditional 3VL (three-value logic). See C for verification. Note that if you specify C<< use Unknown::Values 'fatal' >>, all boolean checks with C values are fatal. Use C to test for unknown values. =head2 Logical Negation !unknown is unknown =head2 Logical And true && unknown is unknown false && unknown is false unknown && unknown is unknown =head2 Logical Or true || unknown is true false || unknown is unknown unknown || unknown is unknown =head1 WHAT IS WRONG WITH UNDEF? Currently C has three different coercions: false, zero, or the empty string. Sometimes those are correct, but not always. Further, by design, it doesn't always emit warnings: $ perl -Mstrict -Mwarnings -E 'my $foo; say ++$foo' 1 $ perl -Mstrict -Mwarnings -E 'my $foo; say $foo + 1' Use of uninitialized value $foo in addition (+) at -e line 1. 1 And because it has no precise definition, C might mean any of a number of things: =over 4 =item * The value's not applicable =item * It's not known =item * It's not available =item * It's restricted =item * Something else? =back In other words, the behavior of C is overloaded, its meaning is ambiguous and you are not guaranteed to have warnings if you use it incorrectly. Now think about SQL's C value. It's problematic, but no alternative has taken hold for simple reason: its meaning is clear and its behavior is unambiguous. It states quite clearly that 'if I don't have a value, I will treat that value as "unknown" via a set of well-defined rules'. An C value behaves very much like the SQL C. It's behavior is consistent and predictable. It's meaning is unambiguous. If used incorrectly, it's a fatal error. =head1 NOTES See also: L This module is an attempt to squeeze three-value logic into Perl, even though it's a bit of an awkward fit. Further, there are several reasons why something could fail to have a value, including "not yet known" (what this module is about), "not applicable" (something the programmer handles explicitly), "privileged" (you can't have the credit card number), an "empty set" (this is not zero), and so on. Empty sets are always equal to one another (there is, technically, only one empty set), but which of the others should be comparable? C<> throws a warning, but allows the program to continue. Is throws the warning because it can't know if this comparison is appropriate or not. For the case of unknown values, we explicitly know the comparison is not appropriate and thus we don't allow it. =head1 TODO Should there be a C variant which dies even if you try to compare unknown to something else? (Currently, we C if we try other, improper operations such as math. =head1 AN INTERESTING THOUGHT Should the C function return an C which returns false in booleans? That might be useful when chaining boolean tests. More importantly, should every C return a sequentially different unknown and thus allow me to say that an unknown is equal to itself but not equal to other unknowns? this means that we could do this: my $value1 = unknown; my $value2 = $value1; if ( $value1 == $value2 ) { ... always true because it's an instance of a *single* unknown } But that gets confusing because we then have this: if ( $value1 == unknown ) { ... always false because unknown generates a new unknown } So an unknown sometimes equals unknowns and sometimes doesn't. It only matches an unknown if it's itself. On the surface this actually seems to be correct, except that we then have this: if ( ( 6 != $value1 ) == ( 7 != $value1 ) ) { ... always false } That has to be false because C<< 6 != $value1 >> I return a C and C<< 7 != $value1 >> should return a different unknown and their cascaded unknown value should fail. However, the following I be true: if ( ( 6 != $value1 ) == ( 6 != $value1 ) ) { ... always true! } Because C<< 6 != $value1 >> should always return the same C. Here's why. We assume, for the sake of argument, that the unknown C<$value1> has a value, but we don't know it. Let's say that value is 4. The above reduces to this: if ( ( 6 != 4 ) == ( 6 != 4 ) ) { Since C<< 6 != 4 >> is true, we get this: if ( 1 == 1 ) { Ah, but what if C<<$value1>>'s hidden value was actually 6? Then we get this: if ( ( 6 != 6 ) == ( 6 != 6 ) ) { Since C<< 6 != 6 >> is false, we get this: if ( 0 == 0 ) { In other words, there's a lot of interesting things we could do, but this would likely involve a fair amount of work breaking out the code for each and every operator and ensuring that it's handled correctly. Of course, this would eat up both memory and performance and certainly be filled with fiddly bugs. =head1 AUTHOR Curtis "Ovid" Poe =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Curtis "Ovid" Poe. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut