Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: DWIM on sub input

by Excalibor (Pilgrim)
on Jul 16, 2003 at 16:01 UTC ( [id://274890]=note: print w/replies, xml ) Need Help??


in reply to DWIM on sub input

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://274890]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-26 08:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found