Skip Menu |

This queue is for tickets about the Number-Zero CPAN distribution.

Report information
The Basics
Id: 81166
Status: open
Priority: 0/
Queue: Number-Zero

People
Owner: Nobody in particular
Requestors: perl [...] toby.ink
Cc:
AdminCc:

Bug Information
Severity: (no value)
Broken in: (no value)
Fixed in: (no value)



Subject: Is it really that difficult to tell the difference between undef and 0??
The pod claims, "The number zero and undef are difficult to determine in Perl", but it doesn't seem that difficult to me... my $var1 = 0; my $var2 = undef; print "\$var1 is zero\n" if $var1 eq 0; print "\$var2 is zero\n" if $var2 eq 0; print "\$var1 is undef\n" if !defined $var1; print "\$var2 is undef\n" if !defined $var2; Of course, I suppose this depends on how you define zero. Does "0.0" count as zero? How about the string "0E0" or the string "0 but true"? Anyway, here are some interesting results where Number::Zero gets things wrong.... use 5.010; use strict; use warnings; use Number::Zero; { package FalseNumber; use overload q[bool] => sub { '' }, q[0+] => sub { $_[0][0] }, fallback => 1, ; } { package TrueNumber; use overload q[bool] => sub { 't' }, q[0+] => sub { $_[0][0] }, fallback => 1, ; } sub test { my $maybe_zero = shift; say "This number is: $maybe_zero"; say "This number plus one is: ", $maybe_zero + 1; say "Number::Zero thinks this number... ", Number::Zero::is_zero($maybe_zero) ? "is zero" : "is not zero"; } test( bless [123] => 'FalseNumber' ); test( bless [0] => 'TrueNumber' );
The following may be a better way of testing for zeroness... sub is_zero { my $maybe = shift; return unless defined $maybe; $maybe + 0 eq 0; } Or if you want to allow is_zero to implicitly operate on $_... sub is_zero { require lexical::underscore; my $maybe = @_ ? shift : ${lexical::underscore()}; return unless defined $maybe; $maybe + 0 eq 0; }
On Wed Nov 14 06:33:49 2012, TOBYINK wrote: Show quoted text
> The following may be a better way of testing for zeroness...
There isn't really any "good" way, because what zero is depends entirely on the caller. As reviewed above, some things may only care for numerical equality to zero (where 0e0, '0 but true','0' (string), 0 (numeric), and 0.0 would all qualify. Other things may care about string vs. numeric, and want to disqualify everything but a literal '0' string. This module aims to put a layer of abstraction in the wrong place.