How can I replace empty elements in an array with "OTHER"? - perl

My list (#degree) is built from a SQL command. The NVL command in the SQL isn't working, neither are tests such as:
if (#degree[$i] == "")
if (#degree[$i] == " ")
if (#degree[$i] == '')
if (#degree[$i] == -1)
if (#degree[$i] == 0)
if (#degree[$i] == ())
if (#degree[$i] == undef)
$i is a counter variable in a for loop. Basically it goes through and grabs unique degrees from a table and ends up creating ("AFA", "AS", "AAS", "", "BS"). The list is not always this long, and the empty element is not always in that position 3.
Can anyone help?
I want to either test during the for loop, or after the loop completes for where this empty element is and then replace it with the word, "OTHER".
Thanks for anything
-Ken

First of all, the ith element in an array is $degree[$i], not #degree[$i]. Second, "==" is for numerical comparisons - use "eq" for lexical comparisons. Third of all, try if (defined($degree[$i]))

Everything that Paul said. And, if you need an example:
my #degree = ('AFA', 'AS', 'AAS', '', 'BS');
$_ ||= 'OTHER' for #degree;
print join ' ' => #degree; # prints 'AFA AS AAS OTHER BS'

If its actually a null in the database, try COALESCE
SELECT COALESCE(column, 'no value') AS column FROM whatever ...
That's the SQL-standard way to do it.

Related

Scala "does not contain" with String split

I am trying Scala for the very first time, not sure how to filter based on not contains.
I have a below query;
.filter(_.get[Option[String]]("status") map(_ split "," contains "Pending") getOrElse(false))
But I want to do something like below;
.filter(_.get[Option[String]]("status") map(_ split "," does not contain "Pending") getOrElse(false))
Can someone please help?
You can use exists and forall to simplify this. These functions return true if a condition is true for any or all elements of a collection.
So the pattern
Option[String].map(???).getOrElse(false)
can be
Option[String].exists(???)
And the condition
!(a split "," contains "Pending")
can be
a.split(",").forall(_ != "Pending")
Applying both of these to the original code gives
.filter(_.get[Option[String]]("status").exists(_.split(",").forall(_ != "Pending")))
But I would recommend a local function to clarify this code:
def notPending(s: String) = s.split(",").forall(_ != "Pending")
.filter(_.get[Option[String]]("status").exists(notPending))
This reads as "take all values where the status option exists and the status is not pending"
Figured out the solution;
.filter(_.get[Option[String]]("status") map(a => !(a split "," contains "Pending")) getOrElse(false))
Thanks.

How to display a user prompt in a calculator program

I'm struggling with a while loop problem. Once the calculation is done, I want the user to be asked whether they want to close the calculator or clear the screen and retry.
How can I use the while loop to do that, if at all?
print ("Calculator Program")
clear="c"
while clear=="c":
one=input("Enter your first number:")
two=input("Enter your second number:")
operator=input("""Choose an operator:
1) Add
2) Subtract
3) Multiply
4) Divide
""")
if operator == '1':
ans=float(one)+float(two)
print (ans)
elif operator == '2':
ans=float(one)-float(two)
print (ans)
elif operator == '3':
ans=float(one)*float(two)
print (ans)
elif operator == '4':
ans=float(one)/float(two)
print(ans)
For the last line in your loop add:
clear = input("[c]lear or [e]xit")
If the user types anything besides "c" the loop will break and the program will finish execution

Expected:: - Using Eclipse with PyDev

I just started up the new version of python, and realized that a lot has changed. Anyways, eclipse comes up with a red "X" mark beside the line numbers saying "Expected::". Could someone please explain what this means, and how I can get rid of it?
This is the code I'm trying to make work with Eclipse and the new Python version:
print "Please insert a valid operator that you want to calculate with."
print "Valid operators are +, -, : and *"
operator = str(raw_input("What's your operator? "))
numb1 = int(raw_input("Please insert the first number:"))
numb2 = int(raw_input("Please insert the second number:"))
if operator == "+":
print numb1 + numb2
elif operator == "*":
print numb1 + numb2
elif operator == "-":
print numb1 - numb2
elif operator == "/":
print numb1 / numb2
On Python3, print is a function, not a statement, so it should be written (for example)
print("Please insert a valid operator that you want to calculate with.")
Also raw_input has been renamed to input so it should be (for example):
numb1 = int(input("Please insert the first number:"))
I ran this program and I saw no problems with it when I ran it on Pydev on Eclipse, even though I ran it on 2.7. perhaps it has something to do with your indentation.
operator = str(raw_input("What's your operator? "))
numb1 = int(raw_input("Please insert the first number:"))
numb2 = int(raw_input("Please insert the second number:"))
if operator == "+":
print numb1 + numb2
elif operator == "*":
print numb1 + numb2
elif operator == "-":
print numb1 - numb2
elif operator == "/":
print numb1 / numb2
I copy pasted your example as well and to fix it I just had to fix the indentation as StackXchangeT did.
However I got Expected:: error when there was missing finishing : at the end of declaration e.g.:
class MyInvalidClass
which is supposed to be:
class MyInvalidClass:
Perhaps you get such error in similar situations where : is needed (just a guess).

When to use "{ }" in C? [K&R Exercise 1.8]

I tried to solve this problem, which is to count the amount of lines, blank spaces, and tabs.
My solution was incorrect because I don't know how to use { }.
main ()
{
int newline;
int tab;
int blank;
int c;
newline = 0;
tab = 0;
blank = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++newline;
if (c == '\t')
++tab;
if (c == 32)
++blank;
printf("lines: %d tabs: %d blanks: %d\n", newline, tab, blank);
}
In my code, only new lines were being counted. Tabs and spaces were never counted.
I know the answer is to add { } around the if statements section. But I only know this because I searched google for the solution.
Perhaps it is just me, but K&R do not really explain when I should use { }.
Can someone explain how I can know to add { } to my above code?
When I read the code, it seems fine without {}. It means I truly don't understand its usage. Why aren't tabs and spaces counted in the above code?
Is there another book on C that you can recommend?
I have no programming experience.
The syntax of a simple if is : if (<condition>) <statement>. The <statement> can be a single statement (as you have in your code) or it can be a block (zero or more statements enclosed in braces). When you have a single statement, it is strictly a question of style whether you surround it with braces—the behavior is the same.
One relatively straightforward "rule of thumb": Look for the semi-colon(s). Referring to your example, starting at the "while", read forward until you see a semi-colon. If you want anything beyond that semi-colon to be executed as part of your while block, you need to wrap it all in curly braces.
Another way to look at it: The semi-colon is a statement terminator. It terminated blank = 0 as your previous statement; it terminates not only the if but also the enclosing while statement. Thus, to execute the following if as part of the while block, you need to enclose the ifs in curly braces.
Oh, and by the way, C and similar languages do not attach syntactic meaning to whitespace. It is at most treated as a separator. Any indentation you choose to apply is for the benefit of the human reader only; it has no significance to the compiler.
Any if/while/for can be followed by a single statement without braces, or any number of statements encapsulated in braces. If you write an if/while/for followed by many statements and no braces, only the first statement falls under the if/while/for. Note that whatever whitespace you use does not matter, it is only for readability.
This is the equivalent of your code if it was written with braces:
while ((c = getchar()) != EOF)
{
if (c == '\n')
{
++newline;
}
}
if (c == '\t')
{
++tab;
}
if (c == 32)
{
++blank;
}
What you want:
while ((c = getchar()) != EOF)
{
if (c == '\n')
{
++newline;
}
if (c == '\t')
{
++tab;
}
if (c == 32)
{
++blank;
}
}
which is equivalent to
while ((c = getchar()) != EOF)
{
if (c == '\n')
++newline;
if (c == '\t')
++tab;
if (c == 32)
++blank;
}
Exclusion of braces serves absolutely no purpose but style. If you are ever in doubt, include the braces.
Braces ({ and }) are used to convert zero or more statements into a single compound statement. Anywhere you wish for a group of statments to be treated as a single statement you should use braces.
For example, a while loop executes a single statement whilst it evaluates to true:
while(some-condition)
statement
Obvious there will be times when you want to execute multiple statements, and this is where you surround them with { and } in order to turn them into a single compound statement.

How to compare the special characters such as ' (' , '/', ' ' in Matlab

I have a character array, cA, and each entry of each stores a single character, such as 'a', '(', '[', and ' '.
My program will iterate this array and perform a certain type of operation based on the content of each entry. For example,
if (cA(i) == 'a') do sth; end
For the characters such as 'a' , 'b', the above character comparison operation is trivial.
But how can I handle the special characters such as '(', '[' and ' '( a blank space)
Can I write something such as
if (cA(i) == ' ')
if (cA(i) == '(')
In general, I suggest comparing strings using STRCMP, e.g.
if strcmp(cA(i),'('), doSomething, end
For your specific case, I suggest a SWITCH/CASE statement. Note that in Matlab, this doesn't fall through like in c; instead, only the "good" case gets executed. In my experience, this helps readability. Thus
for myChar = cA %# this loops over every char in the 1-by-n string
switch myChar
case 'a'
do something
case 'b'
case {'c','d'} %# this is how you handle multiple chars with the same outcome
otherwise
error('char %s not handled',myChar) %# don't forget this
end
end
Did you try it and get an error? Because it works for me:
c = '(';
if(c == '(')
disp('left paren')
end
This prints left paren, as expected.