in reply to Re^2: Celsius to Fahrenheit using s///
in thread Celsius to Fahrenheit using s///

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

Replies are listed 'Best First'.
Re^4: Celsius to Fahrenheit using s///
by Roy Johnson (Monsignor) on Feb 08, 2005 at 19:57 UTC
    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.
Re^4: Celsius to Fahrenheit using s///
by trammell (Priest) on Feb 08, 2005 at 21:32 UTC
    It looks more like you are obfuscating code than writing it.

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

      No. You're using the substitution operator. Only the first portion is a regexp.