Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Bring back the smartmatch operator (but with sane semantics this time)!

by Anonymous Monk
on Jun 11, 2014 at 19:43 UTC ( [id://1089585]=note: print w/replies, xml ) Need Help??


in reply to Bring back the smartmatch operator (but with sane semantics this time)!

A lot of the discussion so far has hinged on how to tell strings from numbers (eq vs. ==), so I'm surprised no-one has mentioned Scalar::Util's looks_like_number() yet... the only downsides I see so far are that it might not be as fast as some other heuristic, and that sometimes I might want to actually compare two numbers as strings explicitly. (Okay one more... looks_like_number recognizes a few strings as numbers, such as "Inf", "Infinity", "NaN" and "0 but true". And it doesn't recognize "1_000" as a number... hmmm. See Perl_grok_number() in numeric.c)

Replies are listed 'Best First'.
Re^2: Bring back the smartmatch operator (but with sane semantics this time)!
by tobyink (Canon) on Jun 11, 2014 at 20:56 UTC

    The string/number heuristic is responsible for some of the oddest behaviour of smart match. Let's take for example the use of $x ~~ @array as an "in" operator.

    sub as_bool { $_[0] ? "true" : "false" } my @greetings = qw( Hi Bye ); say as_bool("Hi" ~~ @greetings); # true say as_bool("Hiya" ~~ @greetings); # false

    OK, everything is working as expected so far. Now let's do something a little more complex...

    push @greetings, 0, 1; say as_bool(0 ~~ @greetings); # true say as_bool(1 ~~ @greetings); # true say as_bool(2 ~~ @greetings); # false say as_bool("Hiya" ~~ @greetings); # true ?!?!
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      Not having memorized the smartmatch table, that looked pretty strange to me at first, but looking at the table, at least it's well-defined... and when I tried it I got a "Argument "Hiya" isn't numeric in smart match" warning, which (although it's not much) is better than it silently matching. But the problem of when to match with == vs. eq remains...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-24 22:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found