Page 1 of 1

Condition in if loop not evaluated correctly

Posted: 17 Sep 2012 10:33
by Marco

Code: Select all

 $orig = readfile ("C:\Dati\Marco\Programmi\Firefox\Data\profile\adblockplus\patterns.ini");
 $first = gettoken ($orig,1,<crlf>);
 $second = gettoken ($orig,2,<crlf>);
 if ($first.<crlf>.$second != "# Adblock Plus preferences".<crlf>."version=4") {
  echo nope!;
 };
I'm trying to parse the filters file of Adblock Plus. Its header is the following

Code: Select all

# Adblock Plus preferences
version=4
so I want to check this before proceeding with further elaborations. But, stepping, I see that the SC engine resolves to this

Code: Select all

if
----
# Adblock Plus preferences
1
version=4
Looks like the truth value is interpolated into the right side of the condition.
Am I doing something wrong or there's a bug?

Re: Condition in if loop not evaluated correctly

Posted: 17 Sep 2012 11:18
by Stefan
Perhaps you have tricked out the engine. Try proper quoting:

"$first<crlf>$second" != "# Adblock Plus preferences<crlf>version=4"

Code: Select all

 $orig = "# Adblock Plus preferences".<crlf>."version=4";     step;
 //readfile ("C:\Dati\Marco\Programmi\Firefox\Data\profile\adblockplus\patterns.ini");
 
 $first  = gettoken ($orig,1,"<crlf>"); 
 $second = gettoken ($orig,2,"<crlf>");

 if ("$first<crlf>$second" != "# Adblock Plus preferences<crlf>version=4") {echo "nope!";}else{msg "yes";}

Re: Condition in if loop not evaluated correctly

Posted: 17 Sep 2012 11:32
by Marco
:oops:
Thanks! Looks like that was the only combination of quotes I hadn't tried before.

Re: Condition in if loop not evaluated correctly

Posted: 22 Sep 2012 15:16
by PeterH
It seems Stefans solution is right - but the reason isn't :shock:

Just to understand what happens the right reason: "Operator Precedence"!
The String Concatenator "." has the lowest precedence of all operators. (Especially it's lower than "!=".)

So:
if ($first.<crlf>.$second != "# Adblock Plus preferences".<crlf>."version=4")
is the same as writing:
if ($first.<crlf>. ($second != "# Adblock Plus preferences") .<crlf>."version=4")
And no doubt: this cannot lead to the correct result.
To make it formally correct (without further change) you would have to write:
if (($first.<crlf>.$second) != ("# Adblock Plus preferences".<crlf>."version=4"))

Of course Stefans solution of putting <crlf> inside (the) double quotes, and by this not needing concatenation characters (conflicting with !=) looks better:
if ("$first<crlf>$second" != "# Adblock Plus preferences<crlf>version=4")


By the way: I would have coded:
if ( ($first != "# Adblock Plus preferences") || ($second != "version=4") )