| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | |||
| 4 | # ABSTRACT: Internal value object for the "Unknown::Values" distribution | ||
| 5 | |||
| 6 | package Unknown::Values::Instance; | ||
| 7 | $Unknown::Values::Instance::VERSION = '0.100'; | ||
| 8 | use Carp 'confess'; | ||
| 9 | |||
| 10 | use 5.01000; | ||
| 11 | my @to_overload; | ||
| 12 | |||
| 13 | BEGIN { | ||
| 14 | my %to_overload = ( | ||
| 15 | sort => [qw{ <=> cmp }], | ||
| 16 | compare => [qw{ <= >= < > lt le gt ge == eq != ne}], | ||
| 17 | math => [qw{ + - * / ** atan2 cos sin exp log sqrt int abs }], | ||
| 18 | string => [qw{ qr x }], | ||
| 19 | files => [qw{ <> -X }], | ||
| 20 | bits => [qw{ << >> & | ^ ~ }], | ||
| 21 | bool => [ 'bool', '!' ], | ||
| 22 | dereference => [qw< ${} @{} %{} &{} *{} >], | ||
| 23 | nomethod => ['nomethod'], | ||
| 24 | ); | ||
| 25 | while ( my ( $method, $ops ) = each %to_overload ) { | ||
| 26 | push @to_overload => $_ => $method foreach @$ops; | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | use overload @to_overload, '""' => 'to_string'; | ||
| 31 | my $CORE_UNKNOWN = __PACKAGE__->new; | ||
| 32 | |||
| 33 | sub to_string { | ||
| 34 | confess("Attempt to coerce unknown value to a string"); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub new { | ||
| 38 | my $class = shift; | ||
| 39 | my $unknown = bless {} => $class; | ||
| 40 | return $unknown; | ||
| 41 | } | ||
| 42 | |||
| 43 | # this helps to prevent some infinite loops | ||
| 44 | sub bool {$CORE_UNKNOWN} | ||
| 45 | |||
| 46 | sub compare { | ||
| 47 | |||
| 48 | # this suppresses the "use of unitialized value in sort" warnings | ||
| 49 | wantarray ? () : 0; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub sort { | ||
| 53 | if ( $_[2] ) { return -1 } | ||
| 54 | elsif ( Unknown::Values::is_unknown( $_[1] ) ) { return 0 } # unnecessary? | ||
| 55 | else { return 1 } | ||
| 56 | } | ||
| 57 | |||
| 58 | sub math { confess("Math cannot be performed on unknown values") } | ||
| 59 | |||
| 60 | sub dereference { | ||
| 61 | confess("Dereferencing cannot be performed on unknown values"); | ||
| 62 | } | ||
| 63 | |||
| 64 | sub files { | ||
| 65 | confess("File operations cannot be performed on unknown values"); | ||
| 66 | } | ||
| 67 | |||
| 68 | sub string { | ||
| 69 | confess("String operations cannot be performed on unknown values"); | ||
| 70 | } | ||
| 71 | |||
| 72 | sub bits { | ||
| 73 | confess("Bit manipulation cannot be performed on unknown values"); | ||
| 74 | } | ||
| 75 | |||
| 76 | sub nomethod { | ||
| 77 | if ( defined( my $operator = $_[3] ) ) { | ||
| 78 | confess("'$operator' operations are not allowed with unknown values"); | ||
| 79 | } | ||
| 80 | else { | ||
| 81 | |||
| 82 | # XXX seems bit manipulation can trigger this | ||
| 83 | confess("Illegal operation performed on unknown value"); | ||
| 84 | } | ||
| 85 | } | ||
| 86 | |||
| 87 | 1; | ||
| 88 | |||
| 89 | __END__ |