1 # $Id: Compare.pm 846 2002-10-25 15:46:01Z richardc $
2 package Number::Compare;
10 my $class = ref $referent || $referent;
11 my $expr = $class->parse_to_perl( shift );
13 bless eval "sub { \$_[0] $expr }", $class;
21 ([<>]=?)? # comparison
23 ([kmg]i?)? # magnitude
25 or croak "don't understand '$test' as a test";
27 my $comparison = $1 || '==';
30 $target *= 1000 if lc $magnitude eq 'k';
31 $target *= 1024 if lc $magnitude eq 'ki';
32 $target *= 1000000 if lc $magnitude eq 'm';
33 $target *= 1024*1024 if lc $magnitude eq 'mi';
34 $target *= 1000000000 if lc $magnitude eq 'g';
35 $target *= 1024*1024*1024 if lc $magnitude eq 'gi';
37 return "$comparison $target";
40 sub test { $_[0]->( $_[1] ) }
48 Number::Compare - numeric comparisons
52 Number::Compare->new(">1Ki")->test(1025); # is 1025 > 1024
54 my $c = Number::Compare->new(">1M");
55 $c->(1_200_000); # slightly terser invocation
59 Number::Compare compiles a simple comparison to an anonymous
60 subroutine, which you can call with a value to be tested again.
62 Now this would be very pointless, if Number::Compare didn't understand
65 The target value may use magnitudes of kilobytes (C<k>, C<ki>),
66 megabytes (C<m>, C<mi>), or gigabytes (C<g>, C<gi>). Those suffixed
67 with an C<i> use the appropriate 2**n version in accordance with the
68 IEC standard: http://physics.nist.gov/cuu/Units/binary.html
74 Returns a new object that compares the specified test.
76 =head2 ->test( $value )
78 A longhanded version of $compare->( $value ). Predates blessed
79 subroutine reference implementation.
81 =head2 ->parse_to_perl( $test )
83 Returns a perl code fragment equivalent to the test.
87 Richard Clamp <richardc@unixbeard.net>
91 Copyright (C) 2002 Richard Clamp. All Rights Reserved.
93 This module is free software; you can redistribute it and/or modify it
94 under the same terms as Perl itself.
98 http://physics.nist.gov/cuu/Units/binary.html