Simple If/else statement - if-statement

Revised Code of full deal.. instead of just the small snippet.. Would $row be the start of the variable?
<?php
error_reporting(-1);
$sql = "SELECT * FROM products Where available like 'Y%' order by manufacturer2, product ASC";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
<--------------------->>
$new_product = "$row"; if ($new_product == "N")
{ echo "No"; } elseif ($new_product == "Y")
{ echo "Yes"; }
<-------->
echo "<div class=reportsalesnew_product>".$row['new_product']."</div>";
echo "<div class=reportsalescase_avail>".$row['case_avail']."</div>";
echo "<div class=reportsalesseasonal>".$row['seasonal']."</div>";
echo "<div class=reportsaleseigth_bbl>".$row['eigth_bbl']."</div>";
echo "<div class=reportsalesquarter_bbl>".$row['quarter_bbl']."</div>";
echo "<div class=reportsaleshalf_bbl>".$row['half_bbl']."</div>";
echo "<div class=reportsalessixth_bbl>".$row['sixth_bbl']."</div>";
echo "<div class=reportsalesthirty_liter>".$row['thirty_liter']."</div>";
echo "<div class=reportsalesfifty_liter>".$row['fifty_liter']."</div>";
echo "</div>";
}
?>

Assuming this is PHP, use the == for equality checks. If you also want to do type checks use the === (recommended).
Also, you might want to look at the boolean data type for this, this is a simple true/false.

Everyone accidentally does it when they begin programming. You've wrote one ='s sign to check for equality but all that is doing is assign it therefore it will always be true(unless it's a constant). Use two ='s for equality, three '='s for type, one '=' for an assignment.

Related

Search pattern for decoding logic

I need to decode logic from a database I reference when determining if an attribute is able to be associated with an item I am defining. The database uses standard logic flow and order of importance. I need to be able to determine nested conditional statements in the strings I pull from the database. For example:
$val = "(red && (blue || yellow)) && black";
The string I'd pull from the database would resemble:
$pull = "red.yellow.black";
I would separate $pull on . and store the values in an array, then I'd verify each value is in the array(s) I generate from the $val string. I am having trouble with the best method for determining how to unpack the nested logic though. Initially, I considered just using a regex, then removing the portion of the logic that has been assessed like so:
($eval) = $val =~ /.*\((.*)?\)/; $val =~ s/(.*)\((.*)?\)(.*)/$1 $2/;
If I do this in a while ($val =~ /\(/) loop, I could probably stack the extracted logic into arrays and evaluate the logical expression in each element to determine if each condition is true for the item I am evaluating, but there's something wrong with my regexp causing the sequence to fail. The ? is not as lazy as I thought, apparently...
my $val = "(red && (blue || yellow)) && black";
my $pull = "red.yellow.black";
my #stack = ();
until ($val !~ /\(/) {
my ($eval) = $val =~ /.*\((.*)?\)/;
push(#stack, $eval);
print "$eval\n";
$val =~ s/(.+)\((.*)?\)(.*)/$1 $2/;
print "$val\n";
}
If I just run the sequence in a perl shell, with some debugging info, I get this:
[bin]$ perl -e 'my $val = "((red && (blue || yellow) && black)"; my $pull = "red.yellow.black"; my #stack = (); until ($val !~ /\(/) { my ($eval) = $val =~ /.*\((.+)?\).?/; push(#stack, $eval); print "EVAL: $eval\n";$pause = <STDIN>;$val =~ s/(.*)\((.*)?\)(.*)/$1 $2/;print "VAL: $val\n"; }'
EVAL: blue || yellow) && black
VAL: ((red && blue || yellow) && black
EVAL: red && blue || yellow
VAL: ( red && blue || yellow
EVAL:
Any input on what I'm doing wrong would be appreciated, and any improvements on efficiency would be greatly appreciated! TIA
Update: Ok, so I just dumbed the whole thing down like this. I lose some of the order of operations, but if I evaluate each statement individually, whenever one of the conditions is broken, I'll pick it up and be able to act on the info accordingly. The code I am going to expand on is below. This would just return the individual components of the expression. I don't like how everything ouside parenthesis is concatenated into the first element, but I guess it still works fundamentally.
my $val = "(red && (blue || yellow)) && black";
$val =~ s/\s+//g;
my #chars = ();
my #ops = ();
while ($val) {
my ($char) = $val =~ /(.)/;
$val =~ s/.//;
push #chars, $char;
}
my $index = 0;
foreach my $char (#chars) {
if ($char =~ /\(/) {
$index++;
} elsif ($char =~ /\)/) {
$index--
}
#assign the character to the index.
$ops[$index] .= $char;
}
s/[()]//g for #ops;
print " #ops\n";
Output:
[/bin]$ perl decode_logic.pl
&&black red&& blue||yellow

shorten preg_match(or) code

I was trying to make a program to match the string which must contains number of 0-9 using regex.
This was correct but it somehow seems long. Do anyone has alternatives for this code?
if($str = (preg_match('/[1]/', $str) && preg_match('/[2]/', $str)
&& preg_match('/[3]/', $str) && preg_match('/[4]/', $str)
&& preg_match('/[5]/', $str) && preg_match('/[6]/', $str)
&& preg_match('/[7]/', $str) && preg_match('/[8]/', $str)
&& preg_match('/[9]/', $str) && preg_match('/[0]/', $str))) {
//do something
}
Simply use a character range: [0-9].
if (preg_match('/[0-9]/', $str)) {
echo 'It does.';
} else {
echo 'It doesn\'t.';
}
If you were ever in a situation where you wouldn't want "6" you could even change it to [012345789] if you really want to.
As Floris mentions, your code is pretty confusing - if you want all the characters to be displayed individually at least once, you can simply use strpos with a loop:
<?php
$match = true;
for ($i = 0; $i < 9; $i++) {
if (strpos($string, (string)$i) === false) {
$match = false;
break; //No need to continue the loop - we already got our answer
}
}
if ($match) {
echo 'Yes!';
} else {
echo 'No!';
}
?>
Alternatively, I apparently already gave you a function to do this?
Looks like you have all the conditions ANDed together. In that following lookahead based regex should work for you:
preg_match('/(?=[^0]*0)(?=[^1]*1)(?=[^2]*2)(?=[^3]*3)(?=[^4]*4)(?=[^5]*5)(?=[^6]*6)(?=[^7]*7)(?=[^8]*8)(?=[^9]*9)./', $str)
If you want to make sure that your string contains all the digits 0-9, you should probably strip anything that is not a digit, then take unique characters only, and make sure the string length is 10. This is more compact than your expression but not necessarily faster. The php function count_chars does much of this work (using mode = 3):
$str = "12345abcde789d9999969";
preg_match_all('/\d+/', $str, $matches);
$distinct = strlen(count_chars(join($matches[0]),3));
if($distinct==10)
{
echo "all ten digits are present<br>";
}
else
{
echo "not all digits are present<br>";
}
echo "there are " . $distinct . " distinct digits<br>";
Output of the above:
not all digits are present
there are 9 distinct digits

regular expression matching perl

I'm trying to match part of a string to a yes or no answer. The string goes either: '{"valid_js":"yes"...' or '{"valid_js":"no"...'. I'm trying to get the "yes" or "no"
Can I just use something like:
/:."yes"/g
Or do I need something more complicated?
Try something like this...
if (m/"valid_js":"(yes|no)"/)
{
# At this point $1 will contain either yes or no
if ($1 eq 'yes')
{
# Answer is yes
}
else
{
# Answer is no
}
}
This is a generic form of regexp:
valid_js["]:["](yes|no)["] -> $1
You can use that regexp to match or replace.
This should help you:
$input = '{"valid_js":"yes"...';
if (($input =~ m/"valid_js":"(.*?)"/) && ($1 eq 'yes')) {
print "1: yes\n";
}
$input = '{"valid_js":"no"...';
if (($input =~ m/"valid_js":"(.*?)"/) && ($1 eq 'yes')) {
print "2: yes\n";
}
You can test the code here.

(La)Tex math parsing for C/C++

I would like to convert parse (la)tex math expressions, and convert them to (any kind of!) scripting language expression, so I can evaluate expressions.
What libraries do you recommend ?
May be it will help - take a look at TeXmacs, especially at a way it interacts with computer algebra systems.
Here is a set of possible options from a similar question. https://tex.stackexchange.com/questions/4223/what-parsers-for-latex-mathematics-exist-outside-of-the-tex-engines
I think that Perl would make a fine choice for something like this, acting on text is one of its fortes.
Here is some info on how to make an exclusive flip-flop test (to find the context between \begin{} and \end{} without keeping those lines), http://www.effectiveperlprogramming.com/2010/11/make-exclusive-flip-flop-operators/
EDIT: So this problem has started me going. Here is a first attempt to create something here is my "math.pl" which takes a .tex file as an arguement (i.e. $./math.pl test.tex).
#!/usr/bin/env perl
use strict;
use warnings;
use Text::Balanced qw/extract_multiple extract_bracketed/;
my $re_num = qr/[+\-\dE\.]/;
my $file = shift;
open( my $fh, '<', $file);
#parsing this out for more than just the equation environment might be easier using Text::Balanced too.
my #equations;
my $current_equation = '';
while(<$fh>) {
my $test;
next unless ($test = /\\begin\{equation\}/ .. /\\end\{equation\}/);
if ($test !~ /(^1|E0)$/ ) {
chomp;
$current_equation .= $_;
} elsif ($test =~ /E0$/) {
#print $current_equation . "\n";
push #equations, {eq => $current_equation};
$current_equation = '';
}
}
foreach my $eq (#equations) {
print "Full Equation: " . $eq->{'eq'} . "\n";
solve($eq);
print "Result: " . $eq->{'value'} . "\n\n";
}
sub solve {
my $eq = shift;
print $eq->{'eq'} . "\n";
parse($eq);
compute($eq);
print "intermediate result: " . $eq->{'value'} . "\n";
}
sub parse {
my $eq = shift;
my ($command,#fields) = extract_multiple(
$eq->{'eq'}, [ sub { extract_bracketed(shift,'{}') } ]
);
$command =~ s/^\\//;
print "command: " . $command . "\n";
#fields = map { s/^\{\ *//; s/\ *\}$//; print "arg: $_\n"; {value => $_}; } #fields;
($eq->{'command'}, #{ $eq->{'args'} }) = ($command, #fields);
}
sub compute {
my ($eq) = #_;
#check arguements ...
foreach my $arg (#{$eq->{'args'}}) {
#if arguement is a number, continue
if ($arg->{'value'} =~ /^$re_num$/) {
next;
#if the arguement is a simple mathematical operation, do it and continue
} elsif ($arg->{'value'} =~ /^($re_num)\ *(?:\ |\*|\\times)?\ *($re_num)$/) {
$arg->{'value'} = $1 * $2;
} elsif ($arg->{'value'} =~ /^($re_num)\ *(?:\+)?\ *($re_num)$/) {
$arg->{'value'} = $1 + $2;
} elsif ($arg->{'value'} =~ /^($re_num)\ *(?:\-)?\ *($re_num)$/) {
$arg->{'value'} = $1 - $2;
} elsif ($arg->{'value'} =~ /^($re_num)\ *(?:\/)?\ *($re_num)$/) {
$arg->{'value'} = $1 / $2;
} else {
#parse it and calc it as if it were its own equation.
$arg->{'eq'} = $arg->{'value'};
solve($arg);
}
}
my #args = #{$eq->{'args'}};
## add command processing here
# frac
if ($eq->{'command'} eq 'frac') {
$eq->{'value'} = $args[0]->{'value'} / $args[1]->{'value'};
return;
}
}
and here is a sample test.tex:
\documentclass{article}
\begin{document}
Hello World!
\begin{equation}
\frac{\frac{1}{3}}{2}
\end{equation}
\end{document}
Maybe using boost::spirit in order to tokenize the expression. You will need to define a huge grammar!
Use a parser generator to create an appropriate parser. Try ANTLR for this, as it includes an IDE for the Grammar, which is very helpful. Using tree rewrite rules, you can then convert the parse tree to an abstract syntax tree.
Start perhaps with the expression evaluator from ANTLR tutorial. I think this is reasonably close enough.

Why this code does not do what I mean?

$w = 'self-powering';
%h = (self => 'self',
power => 'pauә',
);
if ($w =~ /(\w+)-(\w+)ing$/ && $1~~%h && $2~~%h && $h{$2}=~/ә$/) {
$p = $h{$1}.$h{$2}.'riŋ';
print "$w:"," [","$p","] ";
}
I expect the output to be
self-powering: selfpauәriŋ
But what I get is:
self-powering: [riŋ]
My guess is something's wrong with the code
$h{$2}=~/ә$/
It seems that when I use
$h{$2}!~/ә$/
Perl will do what I mean but why I can't get "self-powering: selfpauәriŋ"?
What am I doing wrong? Any ideas?
Thanks as always for any comments/suggestions/pointers :)
When you run
$h{$2}!~/ә$/
In your if statement the contents of $1 and $2 are changed to be empty, because no groupings were matched (there were none). If you do it like this:
if ($w =~ /(\w+)-(\w+)ing$/){
my $m1 = $1;
my $m2 = $2;
if($m2~~%h && $m2~~%h && $h{$m2}=~/ә$/) {
$p = $h{$m1}.$h{$m2}.'riŋ';
print "$w:"," [","$p","] ";
}
}
I expect you will get what you want.
Are you running with use warnings enabled? That would tell you that $1 and $2 are not what you expect. Your second regex, not the first, determines the values of those variables once you enter the if block. To illustrate with a simpler example:
print $1, "\n"
if 'foo' =~ /(\w+)/
and 'bar' =~ /(\w+)/;