Compare values in an array - arrays

I am using perl to work with database queries that return multiple results like this:
select name,percent from table order by percent desc
I want to retrieve only those values in the if condition as in this code:
while (#data=$sth->fetchrow_array()) {
$toto = $data[0];
$percent = $data[1];
foreach $percent (#data) {
if ($percent > 80) {
$output .= $toto.'='.$percent.'%,';
$state = "BAD";
}
elsif ($percent > 60 && $percent < 80){
$output .= $toto.'='.$percent.'%,';
$state = "NOTGOOD";
}
}
}
my $str = "$state $output";
# Display Ouptut
print $str."\n";
undef($str);
exit $ERRORS{$status};
This code only prints the last statement (NOTGOOD); I would like to print BAD for each missing value.
here is the result of the query:
test 40
test2 80
test3 75
test4 90
test5 50
test6 45
and here the print output:
NOTGOOD test4=90%,test2=80%,test3=75%,
all the values are good but wrong state

Your logic is very strange here. But because it's not clear whay you're trying to do, it's impossible for me to fix it for you. I can, however, hopefully explain what your current code is doing in the hope that you can work out how to fix it.
Let's assume that your query returns the following data:
Name,Percent
John,100
Paul,75
George,50
Ringo,25
Now let's step through your code a line at a time.
while (#data=$sth->fetchrow_array()) {
At this point, #data contains "John" and "100".
$toto = $data[0];
$percent = $data[1];
This puts "John" into $toto and "100" into $percent.
foreach $percent (#data) {
This is weird. It iterates over #data putting each element in turn into $percent. So on the first iteration $percent gets set to "John" (overwriting the "100" that you previously put there.
if ($percent > $opt_c) {
I don't know what $opt_c contains. Let's assume it's 50. But $percent contains "John" - which isn't a number. If you have use warnings turned on (and you really should), then Perl will give you a warning at this point as you're trying to do a numerical comparison with something that isn't a number. But Perl will convert your non-number to 0 and do the comparison. 0 isn't greater than 50, so the else branch is executed.
$output .= $toto.'='.$percent.'%,';
$state = "BAD";
}
elsif ($percent > $opt_w && $percent < $opt_c){
Again, I don't know what $opt_w is. Let's assume it's 25. But $percent is still 0 when treated as a number. So this code isn't executed either.
$output .= $toto.'='.$percent.'%,';
$state = "NOTGOOD";
}
}
}
The next time round your inner loop, $percent is set to 100. So your if code is executed and $outer gets set to "John=100%". And $state is set to "BAD". But you never do anything with $state, so it gets overwritten the next time round your outer (while) loop.
Your foreach $percent (#data) line is extremely questionable. I'm really not sure what you're trying to do there. And the reason that you only ever see one $state is because you're (presumably) printing it outside of the loop and only seeing the final value that it gets set to.
It's always a good idea to turn on use strict and use warnings. And then to fix the errors that they will show you.

Related

variable substitution in for each loop- tcl tk programming

I am trying to find out number of elements failed and the results are to be printed in a .csv file.
this is my code,
set n_min_len 10
set n_max_len 50
set n_angle 60
foreach check {"min length" "max length" "angle"} \
fail {$n_min_len $n_max_len $n_angle} {
puts $file [format %30s%10s "$check...." "$fail"]
}
I get output as
min length....$n_min_len
max length....$n_max_len and so on.
Instead I wanted output as
min length....10
max length....50
can someone help me, how to get this.
thank you!!
The problem is with this part:
{$n_min_len $n_max_len $n_angle}
The braces block any substitution. Instead you should write
"$n_min_len $n_max_len $n_angle"
or
[list $n_min_len $n_max_len $n_angle]

TCL Error: can't set "::streamID(1,10,1)": variable isn't array

I have read the thread, Cant read variable, isnt array, and I think may be related somehow, but I can't figure out how. In the following TCL snippet, a three dimensional array ::stream is tested and a value is read. The array contains a scalar ID value. The last line in the snippet creates an error that says
can't set "::streamId(1,10,1)": variable isn't array
while executing
"set ::streamId($chas,$card,$port) $nextId"
(procedure "getNextStreamId" line 28)
I interpret this as meaning $nextId is something other than a scalar and it can't be put into a 3 dimensional array of scalars. Is my interpretation of the error incorrect? I was pretty confident that the array holds scalar values, so I started to think maybe there is some data safety issue here.
# get current streamId
if { [ catch {info exists $::streamId($chas,$card,$port)} ] == 0 } {
if {$::testEnv(verbose) >= $verbLevel} {
logInfo [getProcName] "pre-existing streamId found for: \
\n dutAndPort: $dutAndPort \
\n ixiaPort: {$chas $card $port}\
\n streamId: $::streamId($chas,$card,$port) \
\n incrementing to next one..."
}
set nextId [ mpexpr $::streamId($chas,$card,$port) + 1 ]
} else {
if {$::testEnv(verbose) >= 0} {
logInfo [getProcName] "No pre-existing streamId found for: \
\n\t dutAndPort: $dutAndPort \
\n\t ixiaPort: {$chas $card $port}\
\n\t setting to 1"
}
set nextId 1
}
set curId [ mpexpr $nextId - 1 ]
set ::streamId($chas,$card,$port) $nextId
In your code, I guess you wanted to check if the array ::streamId has the index $chas,$card,$port
info exists $::streamId($chas,$card,$port)
which is incorrect. You should use
info exists ::streamId($chas,$card,$port)
i.e. without dollar sign. Then only the if loop can ensure the existence of the index $chas,$card,$port.
Then, at last you are trying to set the value of the index $chas,$card,$port to $nextId .
set ::streamId($chas,$card,$port) $nextId
which is incoorect, because it kept outside the if loop of variable existence check of the index $chas,$card,$port.
Then the actual error message is referring the fact that there is a scalar variable named streamId exists.
% set ::streamId 1
1
% set ::streamId(1,10,1) 20
can't set "::streamId(1,10,1)": variable isn't array
%
Ensure you don't have the same variable names.

In Python3 display true if search term is in CSV table

I want a user to be able to search for a specific term and if it is in the database a message will be given saying that it is in the database.
This is the code that I have made so far and it runs without errors, but when I enter a search term it always says "We are sorry, but that does not seem to be in our system" and it always says this 3 times. I am using Pycharm as my IDE, but I don't think that this should make a difference.
I am semi new to Python so please be patient with me if I have missed something simple : )
import csv
uIn = input("Please enter a search term: ")
with open('database.csv', 'r') as uFile:
fileReader = csv.reader(uFile, delimiter=',')
for row in fileReader:
if uIn == row[1]: #True
print (uIn + "is in file")
else: #False
print("We are sorry, but that does not seem to be in our system")
----------------------------------------------------------Edit----------------------------------------------------------------
Thank you, #Rahul Bhatnagar, for your answer; it showed me that I needed to switch == with in.
This does answer part of the question, and I have figured out some of the other part, the else statement prints for every row that does not have the uIn inside of it. So say the uIn was on the third row the script would print the #False statement twice and the #True statement once. This is alrightish, but if the uIn is on say the 50th row or the 100th row then there would be 49 or 99 #false statements printed.
I would now say that about 50% of my problem is fixed, the part that is not fixed, is to only print 1 #true or 1 #false statement if it is in the file.
import csv
def search(uIn):
found = false;
with open('database.csv', 'r') as uFile:
fileReader = csv.reader(uFile, delimiter=',')
for row in fileReader:
if uIn in row: #True
found = true;
if(found):
print ("Found the string in file!")
else:
print("We are sorry, but that does not seem to be in our system")
uIn = raw_input("ST: ")
search(uIn)
Where my database.csv file is :
search,terms,go,into,this,file,in,this,format
You're trying to find uIn at position 1 of row in all cases, which is not going to be the situation.

Select groups of lines in file where value of one field is the same

I'm not sure how to word this question so I'll try my best to explain it:
Lets say I have a file:
100001,ABC,400
100001,EFG,500
100001,ABC,500
100002,DEF,400
100002,EFG,300
100002,XYZ,1000
100002,ABC,700
100003,DEF,400
100003,EFG,300
I want to grab each row and group them together where the first value in each row is the same. So all 100001's go together, all 100002's go together, etc.
I just need help figuring out the logic. Don't need a specific implementation in a language.
Pseudocode is fine.
I assume the lines are in order by COL1.
I assume "go together" means they are concatenated into one line.
The logic with pseudocode:
while not EOF
read line
if not same group
if not first line
print accumulated values
start new group
append values
print the last group
In awk you can test it with the following code:
awk '
BEGIN { FS = ","; x=""; last="";}
{
if ($1 != last) {
if (x != "")
print x;
x=$1;
last=$1;
}
x=x";"$2";"$3;
}
END {print x;} '

Perl looping through the Oracle query doesn't produce any data after the first one [duplicate]

This question already has an answer here:
Querying multiple times in Oracle using perl returns only the first query
(1 answer)
Closed 9 years ago.
In the code below, I have #some_array which is an array of arrays which contains text like name. So
#some_array= ([sam, jon, july],[Mike, Han,Tommy],[angie, sita, lanny]);
Now when I query the list like sam jon july first and mike han tommy. Only the execute return the result from the first list others is undef. I don't know why any help will be appreciated.
If I switch the second to first place and run it it will show the first one only. So the problem is it is returning for the first set but for subsequent sets its returning undef. I did enable strict and warnings but it it didn't show any error.
my $pointer;
my $db = $db->prepare_cached("
begin
:pointer := myFun(:A1);
end;
") or die "Couldn't prepare stat: " . $db->errstr;
$db->bind_param_inout(":pointer", \$pointer, 0, { ora_type => ORA_RSET });
for (my $i = 0; $i < #some_array; $i++) {
my #firstarray = #{$some_array[$i]};
my $sql = lc(join(" ", #firstarray));
print "<pre>$sql</pre>\n";
$db->bind_param(":A1", $sql);
$db->execute();
print "<pre>".Dumper($db->execute())."</pre>\n";
}
I don't see how this can work at all, as execute returns the “number of rows affected” and not the result of the prepared statement. You also appear to have overwritten your database handle with the return from prepare_cached, which will destroy the handle and close the connection.
You should be looking at the $pointer variable that you have bound to the SQL variable :pointer that receives the result of the stored procedure call.

Resources