Perl, strings, floats, unit tests, and regular expressions!

OK, as a preface, this question is potentially β€œdumber” than my normal level of question β€” however, this problem has annoyed me over the past few days, so I’ll ask anyway. I will give an example of what my problem is, so I can hope to generalize it to my current problem.

#!/usr/bin/perl -w use strict;

use Test::More 'no_plan';

my $fruit_string = 'Apples cost $1.50';
my ($fruit, $price) = $fruit_string =~ /(\w+)s cost \$(\d+\.\d+)/;

# $price += 0; # Uncomment for Great Success
is ($price, 1.50, 'Great Success');

Now that this is done, I get a message

#   Failed test 'Great Success'
#          got: '1.50'
#     expected: '1.5'

- , is ($price, '1.50', 'Great Success'). - , Test:: Deep cmp_deeply. , , - , , - , - , Perl .

+5
5

Test:: Deep,, num() , ( ):

cmp_deeply(
    $result,
    {
        foo         => 'foo',
        bar         => 'blah',
        quantity    => 3,
        price       => num(1.5),
    },
    'result hash is correct',
);

, , cmp_ok , num() : cmp_deeply($value, num(1.5), 'test name') .

+10

$price :

is ( 0 + $price, 1.50, 'Great Success');
+1

try-and-true ok? , , , is - .

ok($price == 1.5, 'Great Success');

is , ok

ok($price == 1.5, 'Great Success') or diag("Expected \$price==1.5, got $price");
+1

, is($x, $y, $name) cmp_ok($x, 'eq', $y, $name). eq . , cmp_ok '=='. is:

sub is_num {cmp_ok $_[0], '==', $_[1], $_[2]}

, . , :

sub is_num {splice @_, 1, 0, '=='; goto &cmp_ok}

goto &sub , cmp_ok caller, , . goto &sub is_num, cmp_ok , is_num.

, Test:: Magic, Test::More:

use Test::Magic 'no_plan';

... # setup code

test 'fruit price',
  is $price == 1.50;

cmp_ok( $price, '==', 1.50, 'fruit price')

+1

, eq , . 1.50 "1,5", .

, ( ), , , , , eq. .

0

All Articles