"Approx-equal" operator

Mike Samuel mikesamuel at gmail.com
Sun Dec 18 11:18:59 PST 2011


2011/12/17 Dmitry Soshnikov <dmitry.soshnikov at gmail.com>:
> Hi,
>
> Just recently was working with Ruby's code. And found useful again its
> (actually from Perl) "approximately equal" operator: =~

Perl's =~ operator is more comparable to String.prototype.match than
RegExp.prototype.test.

Perl operators can be used in either scalar or list contexts unlike
ecmascript (see perldoc for wantarray) and it's true that =~ produces
a boolean when used in a scalar context, but since match returns null
on zero matches, it can still be used in conditions.  When used in a
non-scalar context, =~ produces a list of the matches:

    perl -e 'my $s = "foo"; print join ",", ($s =~ /o/g)'

prints

   o,o


Even ignoring order of evaluation, desugaring a ~= b to b.test(a)
would cause the seemingly straightforward

   var myRegex = /foo/g;  // Used for a global replace in other code.
   if ("foo" ~= myRegex) { alert(1); }
   if ("foo" ~= myRegex) { alert(2); }
   if ("foo" ~= myRegex) { alert(3); }

to alert 1 and 3 only.


More information about the es-discuss mailing list