dragonchild has asked for the wisdom of the Perl Monks concerning the following question:

I've got a function that accepts a comma-delim string of RGB values between 0 and 255. I need to convert that to an array of 3 values between 0 and 1. This is for a module I'm working on for release to CPAN, so this will be the first time I'm seeing these values. The input-massaging code I have right now is:
my ($color, ...) = @_; $color ||= ''; my @colors = map { s/[^\d.-]//g; $_ ||= 0; $_ < 0 ? 0 : $_ / 255 } (split(/\s*,\s*/, $color, 4), (0) x 3)[0..2];
Can anyone see that I missed anything? Are there any improvements I can make? Am I being too anal or DWIM-ish? Right now, I have no error messages back to the user. Is this a bad thing? As for the line-noise potential, this is the only place this logic will be used. (One idea, one place kind of thing.)

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Replies are listed 'Best First'.
Re: DWIM on sub input
by halley (Prior) on Jul 16, 2003 at 14:22 UTC
    The code is a little hard to read, for something so simple as a set of argument constraints. There's no dishonor in using more statements or more linebreaks to clarify the code.

    I gather your ... represents other arguments not germaine to your question.

    Why not do $color ||= 0? It would help show the numerical default for an unspecified color.

    You allow dash (-) in your filter, but then clamp to zero (I suppose to make sure -4 goes to 0, not 4). You don't clamp to 255, so a color could be 400. Do you want to allow input decimal numbers like 40.3?

    You split up to 4 elements but only want three.

    The method of backfilling your array (via a slice of split(wanted, padding)) is workable but obtuse.

    my $color = shift; my @colors = split(/,/, $color, 3); for (0 .. 2) { $colors[$_] = int($colors[$_] || 0); $colors[$_] = 0 if $colors[$_] < 0; $colors[$_] = 255 if $colors[$_] > 255; $colors[$_] /= 255; }

    Now to review my own version. If I don't want lvalue behaviors from @_, I would probably re-use @_ for the work instead of the above @colors. I used the odd for (0 .. 2) indexing method instead of trying to backfill and slice. I purposely didn't play golf here.

    In my opinion, there's no such thing as "too DWIM-ish" as long as the results are what a reasonable person would expect. "Be lenient in what you accept, be strict in what you produce." When being DWIM, though, it's even more important to have readable code so that the user can understand the magic when it's not DWTM.

    --
    [ e d @ h a l l e y . c c ]

      A few explanations:
      • I split to 4 elements because of the case "1,2,3,4,5,6,7". I want to discard the extra elements.
      • Good catch on the upper bound. Thanks!
      • Yes, I do want to allow 40.3 and 0.01 and the like.
      • I don't want to re-use @_ because of the ... (which are the extra parameters that aren't germane to the discussion). In part, I'm still working the API so I may allow for craziness within @_.
      • The reason for the substitution instead of int is that int throws a warning. Plus, int('a1') != int('1a'), whereas my code will treat them the as the same.

      ------
      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

        Split to 3 elements, because you only want to keep 3. You would have caught (1, 2, 3, 4) from "1,2,3,4,5,6,7".

        D'oh! I was wrong. But "4,5,6,7" == 4 ;)

        --
        [ e d @ h a l l e y . c c ]

Re: DWIM on sub input
by broquaint (Abbot) on Jul 16, 2003 at 14:08 UTC
    You could always move that out to a subroutine e.g
    sub _split_colours { my $color = shift; [ map { s/[^\d.-]//g; $_ ||= 0; $_ < 0 ? 0 : $_ / 255 } (split(/\s*,\s*/, $color, 4), (0) x 3)[0..2] ]; } sub your_subroutine { my($color, ...) = ( _split_colours($_[0]), @_[1 .. $#_] ); ...
    Just means that your_subroutine can get on with doing it's thing _split_colours and do the fiddly colour spltting. Just a thought.
    HTH

    _________
    broquaint

Re: DWIM on sub input
by Aristotle (Chancellor) on Jul 16, 2003 at 16:09 UTC
    my @colours = map { $_ = ($_ || 0) + 0; ( ($_ < 0 ? 0) : ($_ > 255 ? 255) : $_ ) / 255; } split /,/, "$colour,,", 4;

    Makeshifts last the longest.

Re: DWIM on sub input
by Excalibor (Pilgrim) on Jul 16, 2003 at 16:01 UTC

    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;