Array arithmetic in bash - arrays

I have number of arrays in bash, such as arrKey[], aarT[],P[] and I want to do an arithmetic operation with these arrays. As I checked, arrays are working perfectly but, the arithmetic to find array P[] is wrong.
Can anyone help me with this, please?
#The format is C[0] = (A[0,0]*B[0]) + (A[0,1]*B[1])
this is the code that I tried so far.
P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
echo ${P[0]}

There are several issues with your line of code:
P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
There is an additional space after the =, erase it.
P[0]=$(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
It is incorrect to add two elements outside of an Arithmetic expansion.
Remove the additional parentheses:
P[0]=$(({arrKey[0,0]} * {arrT[0]} + {arrKey[0,1]} * {arrT[1]}))
either use a $ or remove the {…} from variables inside a $(( … )):
P[0]=$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))
Even if not strictly required, it is a good idea to quote your expansions:
P[0]="$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))"
Also, make sure that the arrKey has been declared as an associative array:
declare -A arrKey
To make sure the intended double index 0,0 works.

Related

Why is Perl giving "Can't modify string in scalar output" error?

I'm pretty new to Perl and this is my most complex project yet. Apologies if any parts of my explanation don't make sense or I miss something out - I'll be happy to provide further clarification. It's only one line of code that's causing me an issue.
The Aim:
I have a text file that contains a single column of data. It reads like this:
0
a,a,b,a
b,b,b,a
1
a,b,b,a
b,b,b,a
It continues like this with a number in ascending order up to 15, and the following two lines after each number are a combination of four a's or b's separated by commas. I have tied this file to an array #diplo so I can specify specific lines of it.
I also have got a file that contains two columns of data with headers that I have converted into a hash of arrays (with each of the two columns being an array). The name of the hash is $lookup and the array names are the names of the headings. The actual arrays only start from the first value in each column that isn't a heading. This file looks like this:
haplo frequency
"|5,a,b,a,a|" 0.202493719
"|2,b,b,b,a|" 0.161139191
"|3,b,b,b,a|" 0.132602458
This file contains all of the possible combinations of a or b at the four positions combined with all numbers 0-14 and their associated frequencies. In other words, it includes all possible combinations from "|0,a,a,a,a|" followed be "|1,a,a,a,a|" through to "|13,b,b,b,b|" and "|14,b,b,b,b|".
I want my Perl code to go through each of the combinations of letters in #diplo starting with a,a,b,a and record the frequency associated with the row of the haplo array containing each number from 0-14, e.g. first recording the frequency associated with "|0,a,a,b,a|" then "|1,a,a,b,a|" etc.
The output would hopefully look like this:
0 #this is the number in the #diplo file and they increase in order from 0 up to 15
0.011 0.0023 0.003 0.0532 0.163 0.3421 0.128 0.0972 0.0869 0.05514 0.0219 0.0172 0.00824 0.00886 0.00196 #these are the frequencies associated with x,a,a,b,a where x is any number from 0 to 14.
My code:
And here is the Perl code I created to hopefully sort this out (there is more to create the arrays and such which I can post if required, but I didn't want to post a load of code if it isn't necessary):
my $irow = 1; #this is the row/element number in #diplo
my $lrow = 0; #this is the row/element in $lookup{'haplo'}
my $copynumber = 0;
#print "$copynumber, $diplo[2]";
while ($irow < $diplolines - 1) {
while ($copynumber < 15) {
while ($lrow < $uplines - 1) {
if ("|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]) { ##this is the only line that causes errors
if ($copynumber == 0) {
print "$diplo[$irow-1]\n";
#print "$lookup{'frequency'}[$lrow]\t";
}
print "$lookup{'frequency'}[$lrow]\t";
}
$lrow = $lrow + 1;
}
$lrow = 0;
$copynumber = $copynumber + 1;
}
$lrow = 0;
$copynumber = 0;
$irow = $irow + 1;
}
However, the line if ("|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]) is causing an error Can't modify string in scalar assignment near "]) ".
I have tried adding in speech marks, rounded brackets and apostrophes around various elements in this line but I still get some sort of variant on this error. I'm not sure how to get around this error.
Apologies for the long question, any help would be appreciated.
EDIT: Thanks for the suggestions regarding eq, it gets rid of the error and I now know a bit more about Perl than I did. However, even though I don't get an error now, if I put anything inside the if loop for this line, e.g. printing a number, it doesn't get executed. If I put the same command within the while loop but outside of the if, it does get executed. I have strict and warnings on. Any ideas?
= is assignment, == is numerical comparison, eq is string comparison.
You can't modify a string:
$ perl -e 'use strict; use warnings; my $foo="def";
if ("abc$foo" = "abcdef") { print "match\n"; } '
Found = in conditional, should be == at -e line 1.
Can't modify string in scalar assignment at -e line 1, near ""abcdef") "
Execution of -e aborted due to compilation errors.
Nonnumerical strings act like zeroes in a numerical comparison:
$ perl -e 'use strict; use warnings; my $foo="def";
if ("abc$foo" == 0) { print "match\n"; } '
Argument "abcdef" isn't numeric in numeric eq (==) at -e line 1.
match
A string comparison is probably what you want:
$ perl -e 'use strict; use warnings; my $foo="def";
if ("abc$foo" eq "abcdef") { print "match\n"; } '
match
This is the problematic expression:
"|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]
The equals sign (=) is an assignment operator. It assigns the value on its right-hand side to the variable on its left-hand side. Therefore, the left-hand operand needs to be a variable, not a string as you have here.
I don't think you want to do an assignment here at all. I think you're trying to check for equality. So don't use an assignment operator, use a comparison operator.
Perl has two equality comparison operators. == does a numeric comparison to see if its operands are equal and eq does a string comparison. Why does Perl need two operators? Well Perl converts automatically between strings and numbers so it can't possibly know what kind of comparison you want to do. So you need to tell it.
What's the difference between the two types of comparison? Well, consider this code.
$x = '0';
$y = '0.0';
Are $x and $y equal? Well it depends on the kind of comparison you do. If you compare them as numbers then, yes, they are the same value (zero is the same thing whether it's an integer or a real number). But if you compare them as strings, they are different (they're not the same length for a start).
So we now know the following
$x == $y # this is true as it's a numeric comparison
$x eq $y # this is false as it's a string comparison
So let's go back to your code:
"|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]
I guess you started with == here.
"|$copynumber,$diplo[$irow]|" == $lookup{'haplo'}[$lrow]
But that's not right as |$copynumber,$diplo[$irow]| is clearly as string, not a number. And Perl will give you a warning if you try to do a numeric comparison using a value that doesn't look like a number.
So you changed it to = and that doesn't work either as you've now changed it to an assignment.
What you really need is a string comparison:
"|$copynumber,$diplo[$irow]|" eq $lookup{'haplo'}[$lrow]

How do you iterate through multiple arrays and substitute values into an equation?

Don't know if I phrased the question correctly because it's sort of hard to explain. But I have three arrays which represent temperature, salinity, and depth. They're massive so I've put the simplified versions of them below just to get the gist:
t = (np.arange(26)[25:21:-1]).reshape(2,2)
s = (np.arange(34,35,0.25).reshape(2,2))
z = (np.arange(0,100,25).reshape(2,2))
I have this equation here (also stripped down for simplicity):
velocity = 1402.5 + 5*(t) - (5.44 * 10**(-2) * t**(-2)) + (2.1 * 10**(-4) * t**(3)) + 1.33*(s) - (1.56*10**(-2)*z)
What I want to do is to iterate through the values from the t,s,z arrays and have them substituted into the equation to calculate velocity for each case. I want the resultant value to then append into a new array with the same configuration - (2,2) in this case. I can't seem to figure out the best way to approach this, so any sort of feedback would be appreciated.
Cheers!
Just use the same equation as-is with one change:
velocity = 1402.5 + 5*(t) - (5.44 * 10**(-2.0) * t**(-2.0)) + (2.1 * 10**(-4) * t**(3)) + 1.33*(s) - (1.56*10**(-2)*z)
Change: t**(-2) has been changed to t**(-2.0). To better understand why we need to change the type of the exponent see the answer here: https://stackoverflow.com/a/43287598/13389591.
The above gives the output:
[[1576.00116296 1570.56544556]
[1565.15996716 1559.7834676 ]]

perl: precedence of array operations

I'm having some trouble wrapping my head around perl's order of operations. I have the following:
>> my $n = 2;
>> my #arr = (1,2,3,4);
>> print $n/scalar #arr * 100;
0.005
But adding parens:
>> my $n = 2;
>> my #arr = (1,2,3,4);
>> print $n/(scalar #arr) * 100;
50
Looking at the order of operations, it seems as though the first thing that should happen are list operations. In this case, the first one encountered would be scalar #arr, which should return 4. The resulting expression should be print $n/4 * 100, which would follow a standard order of operations and produce 50.
But instead, I assume what is happening is it is performing #arr * 100 first, which produces the scalar value 400, then executed scalar 400, which produces 400, then executes $n/400, giving 0.005.
If the latter is what is happening, then my question is where does scalar fall in the order of operations. If something else is going on, then my question is, well, what?
You can see how Perl parses the code by running it through B::Deparse with -p:
perl -MO=Deparse,-p script.pl
I tried 3 different ways:
print $n/scalar #arr * 100;
print $n/(scalar #arr) * 100;
print $n/#arr * 100;
This was the output:
print(($n / scalar((#arr * 100))));
print((($n / scalar(#arr)) * 100));
print((($n / #arr) * 100));
* is higher than the "named unary operators" (where scalar belongs, check the link) in the precedence table in perlop.
From perlop documentation
In the absence of parentheses, the precedence of list operators such
as print, sort, or chmod is either very high or very low depending on
whether you are looking at the left side or the right side of the
operator. For example, in
#ary = (1, 3, sort 4, 2);
print #ary; # prints 1324
the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple TERM with regard to the preceding expression.
And * operator has a higher precedence 7. than named unary operator 10.
so in scalar #arr * 100 * has higher precedence.

Why does concatenating arrays in Perl produce numbers?

I just tried to concatenate arrays in Perl with the + operator and got strange results:
perl -wE 'say([1, 2, 3] + [4, 5, 6])'
73464360
Doing the same with hashes seems to be a syntax error:
perl -wE 'say({} + {})'
syntax error at -e line 1, near "} +"
Execution of -e aborted due to compilation errors.
What is the result of the 1st expression? Is it documented anywhere?
It is from the numification of references, which produces the memory address of the reference.
perl -E 'say \#a; say 0+\#a; printf "%x\n",0+\#a'
Typical output (though it may change every time you run the program)
ARRAY(0x1470518)
21431576
1470518 <--- same number as in first line
Your hash reference example almost works, but it seems that Perl is parsing the first set of {} blocks as a code block rather than as a hash reference. If you use a unary + and force Perl to treat it as a hash reference, it will work. I mean "work".
perl -E 'say(+{} + {})'
40007168
Because + in Perl is an arithmetic operator only. It forces its arguments to be interpreted as numbers, no matter what. That's why Perl has a separate operator for string concatenation (.).
What you are doing, effectively, is adding the addresses where the arrays are stored.
Array concatenation is accomplished by simply listing the arrays, one after the other. However, if you are using references to arrays ([...]), then you have to dereference them first with #{...}:
perl -wE 'say( #{[1,2,3]}, #{[4,5,6]} )'
But normally you would use array variables and not need the extra syntax.
perl -wE 'my #a = (1,2,3); my #b = (4,5,6); say join("-",#a,#b)'
#=> 1-2-3-4-5-6
The same thing goes for hashes; my %c = (%a,%b); will combine the contents of %a and %b (in that order, so that %b's value for any common keys will overwrite %a's) into the new hash %c. You could use my $c = { %$a, %$b }; to do the same thing with references. One gotcha, which you are running into in your + attempt, is that {} may be interpreted as an empty block of code instead of an empty hash.

Array Operations in perl

Why does the code below return 11 with this :- #myarray = ("Rohan");
Explaination i got was :- The expression $scalar x $num_times, on the other hand, returns a string containing $num_times copies of $scalar concatenated together string-wise.
So it should give 10 not 11 ...
code is as below :-
print "test:\n";
#myarray = ("Rohan"); # this returns 11
###myarray = ("Rohan","G"); this returns 22
#myarray2 = (#myarray x 2);
#myarray3 = ((#myarray) x 2); #returns Rohan,Rohan and is correct
print join(",",#myarray2,"\n\n");
print join(",",#myarray3,"\n\n");
What’s happening is that the x operator supplies scalar context not just to its right‐hand operand, but also to its left‐and operand as well — unless the LHO is surrounded by literal parens.
This rule is due to backwards compatibility with super‐ancient Perl code from back when Perl didn’t understand having a list as the LHO at all. This might be a v1 vs v2 thing, a v2 vs v3 thing, or maybe v3 vs v4. Can’t quite remember; it was a very long time ago, though. Ancient legacy.
Since an array of N elements in scalar context in N, so in your scenario that makes N == 1 and "1" x 2 eq "11".
Perl is doing exactly what you asked. In the first example, the array is in scalar context and returns its length. this is then concatenated with itself twice. In the second example, you have the array in list context and the x operator repeats the list.

Resources