[Melbourne-pm] given/when and smartmatch

Toby Corkindale toby.corkindale at strategicdata.com.au
Thu May 30 00:28:44 PDT 2013


On 30/05/13 12:42, Kahlil Hodgson wrote:
>
> On Thu, May 30, 2013 at 12:18 PM, Toby Corkindale
> <toby.corkindale at strategicdata.com.au
> <mailto:toby.corkindale at strategicdata.com.au>> wrote:
>
>     I wondered how you feel about this?
>
>
> Smart match, as currently defined, fails the 'obviousness' test for me.
> Too many special cases for me to be immediately clear what was going to
> happen with a particular piece of code.  Kept having to have to check
> the documentation.  Not good for something that could become a common
> construct.

I agree that the version implemented is confusing, but I like the 
overall idea.
I think it's trying to make up for the historical mistake of splitting 
up numeric and string equality into separate operators, and the 
confusing (and arguably wrong) behaviour of comparing arrays or 
references using the other equality operators.

As much as people say smartmatch was not obvious, it does a better job 
than the existing options when you look at it this way:

# These give the opposite result to what you'd expect, ie they are both 
true:
[1,2,3] != [1,2,3]
(1,2,3) == (4,5,6)

#This is a warning or error depending on perl version:
"fooba" == "fooba"

# These do make sense:
[1,2,3] ~~ [1,2,3]
"fooba" ~~ "fooba"


> I don't really mourn the loss of given/when, because the code I write
> doesn't lend itself to switch-like statements that can't be handled
> better with lookup tables.  Perhaps there are some design patterns I'm
> missing?

It can be quite neat for certain types of incoming data.
given ($input) {
   when (/complex_match/) { ... }
   when (/another_match/) { ... }
   when ($have_seen_you_before) { push $have_seen_you, $val }
   when (undef) { something else }
   when (expensive_check($_)) { .. }
   default { ok.. }
}

You can totally implement such a pattern in other ways; sometimes they 
are better too, but sometimes this is a quick, efficient method.

-T


More information about the Melbourne-pm mailing list