Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, strings, floats, unit testing and regexps!

Tags:

perl

OK, as a preface this question potentially is 'stupider' than my normal level of question - however this problem has been annoying me for the last few days so I'll ask it anyway. I'll give a mock 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 when this is run I get the message

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

To make the test work - I either uncomment the commented line, or use is ($price, '1.50', 'Great Success'). Both options do not work for me - I'm testing a huge amount of nested data using Test::Deep and cmp_deeply. My question is, how can you extract a double from a regexp then use it immediately as a double - or if there is a better way altogether let me know - and feel free to tell me to take up gardening or something lol, learning Perl is hard.

like image 545
Chris R Avatar asked Feb 09 '11 22:02

Chris R


2 Answers

You're already using Test::Deep, so you can simply use the num() wrapper to perform a numerical rather than stringwise comparison (it even lets you add in a tolerance, for comparing two inexact floating point values):

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

For normal comparisons done separately, cmp_ok will work, but num() is still available: cmp_deeply($value, num(1.5), 'test name') still works.

like image 143
Ether Avatar answered Sep 25 '22 14:09

Ether


Force $price to be interpreted as a number:

is ( 0 + $price, 1.50, 'Great Success');
like image 42
Tim Avatar answered Sep 24 '22 14:09

Tim