How to call i in a for loop? [duplicate] - bash

This question already has answers here:
What is the difference between $(command) and `command` in shell programming?
(6 answers)
Closed 7 years ago.
So, this question seems a-specific. It is, because I'm not a BASH-programmer, rather a Biologist-turned-writing-some-useful-scripts-for-my-daily-work-scripter. Anyway. Say, I have a for loop, like so:
for CHR $(seq 1 22); do
echo "Processing chromosome ${CHR}";
done
I used to write `seq 1 22` but now I've learned to write $(seq 1 22). Clearly there is a difference in terms of the way you write it. But what is the difference in terms in computer language and interpretation? Can someone explain that to me?
The other thing I learned by simply doing on the command line on our computer cluster, was to call "i" differently. I used to do: $CHR. But when I'd have a file name sometext_chr to which I'd like to add the number (sometext_chr$CHR) that wouldn't work. What does work is sometext_chr${CHR}. Why is that? Can someone help me explain the difference?
Again, I know the question is a bit a-specific - I simply didn't know how to otherwise frame it - but I hope someone can teach me the differences.
Thanks and best!
Sander

The $(...) can be nested easily, as the parentheses clearly indicate where an expression starts and ends. Using `, nesting is not so simple, as the start and end symbols are the same.
Your second example is probably from memory, because it's incorrect. sometext$chr and sometext${chr} would both work the same way. Perhaps what you really meant was a situation like this:
$chr_sometext
${chr}_sometext
The key point here is that _ is a valid character in a variable name. As a result, $chr_sometext is interpreter as the value of the variable chr_sometext. In ${chr}_sometext the variable is clearly chr, and the _sometext that follows it is a literal string value. Just like if you wrote $chrsometext you wouldn't assume that the chr is somehow special. This is the reason you have to add the clarifying braces.

Related

Comparing values "in the different" in VBscripting Photoshop [duplicate]

This question already has answers here:
Compare two values
(3 answers)
Closed 1 year ago.
In VB Script in Photoshop, is it possible to implement conditionals such as:
if A<>B Then
....code....
End if
I can compare equals, i.e. "if A=B etc etc", but I cannot find the syntax for comparing in the "different".
I have tried different combinations of syntax in line with what I know of coding (aka batting in the dark) to no avail. BTW, this apparent limitation would not matter except that there is no GOTO avalibale here statements that I know of.
Regards,
Of course that VBScript can use both equals and differents.
Example you showed is correct :
if (string<>"") then
...
end if
Can you show a sample of code you used ? Maybe the issue is somewhere else, like comparaison different kind of values (string vs number).

In a C Make script, how to increment a variable? [duplicate]

This question already has an answer here:
How to increment variable
(1 answer)
Closed 4 years ago.
I was expecting a function like "increment(VAR)" but couldn't find any.
MATH(EXPR VAR "${VAR}+1")
Review this
How to increment variable
https://cmake.org/cmake/help/v2.8.8/cmake.html#command%3amath
The proffered solution won't work in every context, but only in the context of an ACTION that corresponds to a given target.
Also, not sure what all this MATH jazz is, how about using backticks (prefer $()-notation, but that's ksh-specific):
`expr ${VAR} + 1`
You can barely see the backticks before the 'e' and after the '1', but they're there.

What's the purpose of `do` in the while loop? [duplicate]

This question already has answers here:
Ruby while syntax
(2 answers)
Closed 7 years ago.
A while loop works with or without do. Please explain why the following two snippets works the same way.
Without do
i = 1
while i < 5
i = i + 1
end
With do
i = 1
while i < 5 do
i = i + 1
end
The non-theoretical answer is quite simply: because the Ruby Syntax Guide said so.
The language syntax guide defines the do keyword as optional for both while and until loops.
From what I understand - and it is mostly a theory - allowing the do to be optional rather than required is mostly for compatibility and allowing for harmonic syntax within the language.
I think of it as an acknowledgment for the "gray" areas, where things are less absolute. The same is done in physics, where light behaves both as a particle and as a wave and we should acknowledge both aspects.
Coming from different languages and school of thought, while is somewhere between a pure keyword (like if) and a method (like loop, which is defined under the Kernel module)
if statements do not require a do to begin a block of code and under the same logic, while loops wouldn't require a do keyword.
This is while as a keyword.
On the other hand, loop requires the do keyword (or the {block}), so why shouldn't while have the same semantics?
This is while as a method (as far as syntax goes).
Ruby is about making the programmer happy. Allowing the do to be optional makes all programmers happy and doesn't require that the Ruby programmer resign themselves to just one school of thought related to the nature of while.
x = 0
while x<3 do puts "hello"; x+=1 end
--output:--
hello
hello
hello
The do is optional, and can be used to clarify a code as in the answer to be on one line. Separation can be done with a do, newline, \, or semicolon.

How would make this more elegant [duplicate]

This question already has an answer here:
How can I more elegantly remove duplicate items across all elements of a Ruby Array?
(1 answer)
Closed 8 years ago.
I have this piece of code in an application and was told to make it more elegant but have no idea how to make it better
self.join(" ").split(" ").uniq
Any suggestion will be much appreciated.
self is an array
flat_map(&:split).uniq
flat_map runs a block over an array, and concatenates all the resulting arrays.
flat_map(&:split) is equivalent to calling s.split on every argument, which happens to do the exact same thing as s.split(' '), (unless you redefine $;, but please don't do that).
We don't need self, so we omit it.

defensive coding practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Ever since I first wrote
if ($a = 5) {
# do something with $a, e.g.
print "$a";
}
and went through the normal puzzling session of
why is the result always true
why is $a always 5
until I realized, I'd assigned 5 to $a, instead of performing a comparison.
So I decided to write that kind of condition above as
if (5 == $a)
in other words:
always place the constant value to the left side of the comparison operator, resulting in a compilation error, should you forget to add the second "=" sign.
I tend to call this defensive coding and tend to believe it's a cousin to defensive-programming, not on the algorithmic scale, but keyword by keyword.
What defensive coding practices have you developed?
One Week Later:
A big "thank you" to all who answered or might add another answer in the future.
Unfortunately (or rather fortunately!) there is no single correct answer. For that my question was to broad, asking more for opinions or learnings of experience, rather than facts.
Always use braces:
if(boolean)
oneliner();
nextLineOfCode();
is not the same as:
if(boolean)
{
oneliner();
}
nextLineOfCode();
If oneliner() is a #defined function, and it isn't defined then your next line of code suddenly becomes subject to the if(). Same thing applies to for loops etc. With braces then the next piece of code never unintentionally becomes conditional on the if/for etc.
The top 3 defensive coding practices I employ are
unit testing
unit testing
unit testing
There is no better defense for the quality of your code than a good unit test to back you up.
This is a simple and obvious one, but I NEVER EVER NEVER repeat the same string constant twice in my code, cause I KNOW that if I do I will be spelling one of them wrong :) Use constants, people!
Always put curly braces after an if/for/while ... even if there's only one single statement after. BTW D. Crockford thinks it's better too: Required blocks
When comparing a string with a constant, write
if ("blah".equals(value)){}
instead of
if (value.equals("blah")){}
to prevent a NullPointerException. But this is the only time I use the suggested coding-style (cause "if (a = 1)..." is not possible in Java).
One of the things I always try to remember when I am in the Javascript world is to always start the return value of a function on the same line as the return key word.
function one(){
return {
result:"result"
};
}
function two(){
return
{
result:"result"
};
}
These 2 functions will not return the same value. The first function will return an Object with a property results set to "result". The second function will return undefined. It's a really simple mistake and it happens because of Javascript's over-zealous Semi-Colon Insertion strategy. Semi-colons are semi-optional in Javascript and because of this the Javascript engine will add semi-coons where it thinks it's should be. Because return is actually a valid statement a semi-colon will be inserted after the return statement and the rest of the function will essentially be ignored.
From my blog:
Think positive and return early plus avoid deep nesting. Instead of
if (value != null) {
... do something with value ...
}
return
write
if (value == null) {
return
}
... do something with value ...
Avoid "string constants" (i.e. the same text in quotes in more than one place). Always define a real constant (with a name and an optional comment what it means) and use that.
Personally, I dislike this defensive style, it makes the code hard ro read.
VC compiler warning level 4 will spot this (possible) error.
"warning C4706: assignment within conditional expression"
You can enable just this specific compiler warning, at any level:
#pragma warning(3,4706)
Always initialize variables
Use const wherever I can (without using mutable)
Avoid bare dynamic allocation of memory or other resources
Always use curly braces
Code use-cases and tests for any class before coding implementation
Turn on as many useful warnings as I can (-Wall -Wextra -ansi -pedantic -Werror at a minimum)
Use the simplest tool that solves the problem (in my current environment, that's bash -> grep -> awk -> Python -> C++).
I stopped using languages where you can do
if a = 5: print a
This has saved me tons of headaches =).
On a more serious note... I now always write the curly braces right after I write my ifs and for loops, and then fill them in afterwards. This makes sure my brackets are always aligned.
Returning a copy of a mutable object, i.e. a copy of an array, not the mutable object itself.
Couple things:
Yes, the 1-line blocks. Use the braces... heck, most good IDE's will make em for you.
Comment your code after you write it, or re-read your comments if you did it ahead of time. Make sure your code still does what the comments say.
Unit testing is a great fallback to re-reading your code.
Always log an exception... or, NEVER catch an exception without saying so, at least in debug.
Avoid unnecessary test.
Example
if(bool == true)
Pointer checks if(pointer)
EDIT:
if(pointer) is not readable so nowadays I prefer if(NULL != pointer)
Installed Resharper ;)
Then I don't need to write "5 == a" to get warned if I did something wrong :)

Resources