Thanks to everyone for their wisdom. I agree that s/// isn't in principle the best way to do this, I just was playing with the eval functionality in RHS (right hand side). Hey, if it's good enough for Nathan Torkington (see url at top of comments), it should be good enough for me, right?

But I kept getting comments that there was something wrong with the regex. First, it didn't work with negatives. Then, it didn't work with decimals. Then, it worked *only* with decimals.

Well, I got tired of this back and forth, so here's the same code using Damian Conway's Regexp::Common::Number in the LHS (left hand side). If there's still some issue here, submit a bug report to CPAN. ;)

use strict; use warnings; use Regexp::Common; # From http://prometheus.frii.com/%7Egnat/yapc/2000-stages/slide31.htm +l # Fixed a typo in the regex (Nathan forgot to escape the forwardslash. +) while (<DATA>) { chomp; my $celsius = my $fahrenheit = $_; #was $fahrenheit =~ s|(\d+)C|($1*9/5)+32 . "F"|ge; # But that didn't work with decimals #was $fahrenheit =~ s|(\d+\.\d+)C|($1*9/5)+32 . "F"|ge; #but that required decimals #This is getting ridiculous, so let's just use Damian Conway's Regex +p::Common $fahrenheit =~ s|($RE{num}{real})C|($1*9/5)+32 . "F"|ge; print "$celsius is $fahrenheit\n"; } #Outputs: #-2C is 28.4F #-1.5C is 29.3F #-1C is 30.2F #-1.0C is 30.2F #0C is 32F #0.0C is 32F #.1C is 32.18F #0.1C is 32.18F #1C is 33.8F #+1C is 33.8F #1.5C is 34.7F #+1.5C is 34.7F #2C is 35.6F __DATA__ -2C -1.5C -1C -1.0C 0C 0.0C .1C 0.1C 1C +1C 1.5C +1.5C 2C

In reply to Celsius to Fahrenheit using Regexp::Common by tphyahoo
in thread Celsius to Fahrenheit using s/// by tphyahoo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.