Microsoft Scripting Guys failed at Perl… big time
2 February 2008So don't get me wrong, I'm still a great MS fan and everything… but come on… they could have tested their script before publishing it!
the failure: (source microsoft.com)
That's the original url but I don't think that error will last long on that page
So, what's wrong, and what would be correct?
Let's take their code:
$strValue = "ABCDE5FGHIJKLM";
if ( $strValue == /[0-9]/ )
{print "This value contains a number. \n";}
here's what you need to know to understand why it won't work:
perl has an awesome variable ( $_ ) that is somehow the default input value
$str="Perl ";
$_="rocks";
print $str;
print;
the first print will print $str like we want to, and the second one will print $_ because we didn't specify another variable.
It works the same for regular expression, since == is not the correct operator to apply a regex on a string, it'll evaluate the $_ variable.
== is the equality operator that returns true if the left argument is numerically equal to the right argument.
So they are trying to compare the result of a regular expression that searches a number in an empty variable (remember $_), which obviously returns false, to a string using the numeric equality operator (I havn't told you that before, but obviously any string is seen as false for the == operator)
if(false == false)
=> true, so even if there's no number in the $strValue variable, it'll say "This value contains a number."
So here's the code that actually works:
$strValue = "ABCDE5FGHIJKLM";
if ( $strValue =~ /[0-9]/ )
{print "This value contains a number. \n";}
=~ is NOT a comparison operator!
Binary "=~" binds a scalar expression to a pattern match. (perlop)
that basically means that the regular expression is applied to the variable that is on the left side of the =~ operator.