in reply to Celsius to Fahrenheit using s///

I suppose the point of that little exercise is to show how /e works.
But for practical purposes, it's pretty useless:
16.5C is 16.41F -40C is -104F

Replies are listed 'Best First'.
Re^2: Celsius to Fahrenheit using s///
by Tanktalus (Canon) on Feb 08, 2005 at 15:31 UTC

    Almost as easy to fix it as to find the problem ;->

    use strict; use warnings; # From http://prometheus.frii.com/%7Egnat/yapc/2000-stages/slide31.htm +l # Fixed a typo in the regex (Nathan forgot to escape the forwardslash. +) # Fixed number problems - allow +/-, and decimals. Exponentials still + not allowed. while (<DATA>) { chomp; my $celsius = my $fahrenheit = $_; $fahrenheit =~ s|([+-]?(?:\d*\.)?\d+)C|($1*9/5)+32 . "F"|ge; print "$celsius is $fahrenheit\n"; } #Outputs: #12C is 53.6F #13C is 55.4F #14C is 57.2F #15C is 59F #-40C is -40F #+32C is 89.6F #.5C is 32.9F #15.8C is 60.44F __DATA__ 12C 13C 14C 15C -40C +32C .5C 15.8C

      Using the /e modifier of a regex for such uses is just plain wrong. It looks more like you are obfuscating code than writing it. Much better written in a form such as the following (mine will also do reverse conversions -- F to C):

      #!/usr/bin/perl -w use strict; while (<DATA>) { chomp; next unless (m!\A([+-]?(?:\d*\.)?\d+)([CF])\z!); print "$_ is ", ( $2 eq 'C' ? $1 * 9 / 5 + 32 . 'F' : ($1 - 32) * 5 / 9 . 'C' ), $/; } __END__ 12C 13C 14C 15C -40C +32C .5C 15.8C 60.44F 55.4F -.7F
        Is this better, or worse?
        while (<DATA>) { chomp; my $was = $_; my %formulae = (C => sub { ((shift() * 9/5) + 32).'F' }, F => sub { ((shift() - 32) * 5/9).'C' }); s{(.*)([CF])}{${\$formulae{$2}($1)}}; # Update: look, ma! No "e" print "$was is $_\n"; } __DATA__ 12C 13C 14C 15C -40C +32C .5C 15.8C 60.44F 55.4F -.7F

        Caution: Contents may have been coded under pressure.
        It looks more like you are obfuscating code than writing it.

        Come on, we're converting Celsius to Fahrenheit in a regexp here! :^)