Hi there,

Why not something in the line of this? :

sub rgb2percent { my $string = shift; my $MAX_COLOR = 255; my ($r,$g,$b) = $string =~ m/(\d*\.?\d+) # 1st number .*\,[^\d]* # the comma and spaces, - etc (\d*\.?\d+) # 2nd number .*\,[^\d]* # again garbage or formatting (\d*\.?\d+)/x; # 3rd and final number my %mask = ( r => $r, g => $g, b => $b); for my $color ( keys %mask ) { $mask{$color} = ( $mask{$color} % ($MAX_COLOR+1) ) / $MAX_COLOR +; } return [$mask{r}, $mask{g}, $mask{b}]; }

I think this is easy to follow. We first match for three non negative real numbers (allowing numbers such as .01). If it's between 0 and 255 why suppose -5 is zero instead of a typoed '-' sign? The client should know the contract better and write the string properly. Anyway, it admits strings of the form "255, 125,and 7.34" for example (so much for flexibility).

We put the results into a properly named hash (very useful if we need to make more calculations with the colors, not just this simple thing). We normalize the values in-place and return what we want, a ref to an array (we can return a list wich will work as well, but a ref seems tidier).

Granted, it's more verbose, but it's also much cleaner, I think. Want a golfer solution? Easy:

my @colors = map { ($_%256)/255 } $_[0] =~ m/(\d*\.?\d+).*\,[^\d]*(\d* +\.?\d+).*\,[^\d]*(\d*\.?\d+)/;

Best regards,

Update: oops, forgot to normalize to 1, corrected, now 400.23 => 144. They definitely should read the sub contracts... :-)

--
our $Perl6 is Fantastic;


In reply to Re: DWIM on sub input by Excalibor
in thread DWIM on sub input by dragonchild

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.