implicit declaration in libreoffice basic - basic

I've tried the example code here (a = b + c). Suprisingly, the reality is not the expected behavior.
With Win7 and LO 4.4.2.2, I see a and b are declarated as integers whose values are 0, and c is empty.
With Ubuntu 16.04 and LO 5.1.6.2, they are all empty.
Any idea how to explain the first case ?

From https://help.libreoffice.org/Basic/Using_Variables:
As soon as the variable has been declared, it is automatically set to the "Null" value. Numeric variables are automatically assigned the value "0" as soon as they are declared.
As the link in the question seems to suggest, implicit initialization is bad programming practice in Basic. So strange results should not be surprising when using old versions.
With Perl, $a = $b + $c; sets the value of $a to zero because it is a mathematical result, and $b and $c are initialized to an empty string. Perl has a long history of facilitating undeclared variables, although nowadays use strict is recommended.

Related

Evaluate a string read from a file in perl

Made up example (perl):
my $x = read_input_from_file();
# $x now contains string $ENV{SOMETHING}/dir/$ENV{SOMETHING_ELSE}
my $y = eval($x); # doesnt work
How can I get value of string contained in $x in the script?
So far I have tried using eval which doesn't generate any output. I am hoping that something already exists in perl and these string expressions do not need to be parsed and evaluated.
The "string" eval is a little specific:
eval in all its forms is used to execute a little Perl program.
...
In a string eval, the value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program.
So this evaluates code, and with a variable to be evaluated containing a string literal we have a "bareword" ("Unquoted string") which is generally no good. In your case, those / in $x cause additional trouble.
If the content of the variable to evaluate is a string literal (not code) it need be quoted
my $y = eval q(") . $x . q("); # double-quote so that it interpolates
I use the operator form of a single quote, q(). Quoted under it is a double-quote since $x itself seems to contain variables that need be evaluated (interpolated).
Keep in mind that running code from external sources can be a serious security problem.

String formatting in python 3 without print function

Trying to understand how "%s%s" %(a,a) is working in below code I have only seen it inside print function thus far.Could anyone please explain how it is working inside int()?
a=input()
b=int("%s%s" %(a,a))
this "%s" format has been borrowed from C printf format, but is much more interesting because it doesn't belong to print statement. Note that it involves just one argument passed to print (or to any function BTW):
print("%s%s" % (a,a))
and not (like C) a variable number of arguments passed to some functions that accept & understand them:
printf("%s%s,a,a);
It's a standalone way of creating a string from a string template & its arguments (which for instance solves the tedious issue of: "I want a logger with formatting capabilities" which can be achieved with great effort in C or C++, using variable arguments + vsprintf or C++11 variadic recursive templates).
Note that this format style is now considered legacy. Now you'd better use format, where the placeholders are wrapped in {}.
One of the direct advantages here is that since the argument is repeated you just have to do:
int("{0}{0}".format(a))
(it references twice the sole argument in position 0)
Both legacy and format syntaxes are detailed with examples on https://pyformat.info/
or since python 3.6 you can use fstrings:
>>> a = 12
>>> int(f"{a}{a}")
1212
% is in a way just syntactic sugar for a function that accepts a string and a *args (a format and the parameters for formatting) and returns a string which is the format string with the embedded parameters. So, you can use it any place that a string is acceptable.
BTW, % is a bit obsolete, and "{}{}".format(a,a) is the more 'modern' approach here, and is more obviously a string method that returns another string.

Makefile macro modifier

I am totally confused about the following macro modifier in a Makefile I have come onto,
TOOLS = $(TOOL_ROOTS:%=$(OBJDIR)%$(TOOL_SUFFIX))
Here
TOOL_ROOTS=some filename prefixes
OBJDIR=$HOME/obj/
TOOL_SUFFIX=.so
Can someone tell me what this line actually means?
TOOL_ROOTS must be getting assigned some value other than the empty string at some point or that does nothing (which I'll show in a moment).
So first things first just expanding the variables takes us from:
TOOLS = $(TOOL_ROOTS:%=$(OBJDIR)%$(TOOL_SUFFIX))
to:
TOOLS = $(:%=~/obj%.so)
(which we can immediately see doesn't look right, and as I'll explain in a moment doesn't do anything)
So lets pretend it has a value instead.
TOOL_ROOTS = shovel axe hammer
And try the expansion again:
TOOLS = $(shovel axe hammer:%=~/obj%.so)
(That OBJDIR definition looks odd also. I would expect it to be ~/obj/ or something... and that's ignoring that ~ is a bad choice here and that $HOME would be much better.)
The next thing we need to know is what that syntax is all about. Well it is a Substitution Reference.
A substitution reference substitutes the value of a variable with alterations that you specify. It has the form ‘$(var:a=b)’ (or ‘${var:a=b}’) and its meaning is to take the value of the variable var, replace every a at the end of a word with b in that value, and substitute the resulting string.
When we say “at the end of a word”, we mean that a must appear either followed by whitespace or at the end of the value in order to be replaced; other occurrences of a in the value are unaltered. For example:
foo := a.o b.o c.o
bar := $(foo:.o=.c)
sets ‘bar’ to ‘a.c b.c c.c’. See Setting Variables.
A substitution reference is actually an abbreviation for use of the patsubst expansion function (see Functions for String Substitution and Analysis). We provide substitution references as well as patsubst for compatibility with other implementations of make.
Another type of substitution reference lets you use the full power of the patsubst function. It has the same form ‘$(var:a=b)’ described above, except that now a must contain a single ‘%’ character. This case is equivalent to ‘$(patsubst a,b,$(var))’. See Functions for String Substitution and Analysis, for a description of the patsubst function.
For example:
foo := a.o b.o c.o
bar := $(foo:%.o=%.c)
sets ‘bar’ to ‘a.c b.c c.c’.
So, the first % there is matching the entirety of every word in the value of the variable (here shovel axe hammer) and then replacing each value with the expansion of the second part.
So shovel becomes ~/objshovel.so, etc. and we end up with:
TOOLS = ~/objshovel.so ~/objaxe.so ~/objhammer.so
See what I meant about OBJDIR being odd before? OBJDIR=~/obj/ would have left us with this instead:
TOOLS = ~/obj/shovel.so ~/obj/axe.so ~/obj/hammer.so
which makes a lot more sense to me.

i'm confused about languages category, can anyone please explain?

Which of the following statements is FALSE?
(A) In statically typed languages, each variable in a program has a fixed type
(B) In un-typed languages, values do not have any types
(C) In dynamically typed languages, variables have no types
(D) In all statically typed languages, each variable in a program is associated with values of only a single type during the execution of the program
Can you please explain the theory as well?
C) (In dynamically typed languages, variables have no types) Is false.
The variable has a type, however it is simply not stated or decided until run time. This implies there is no type checking prior to running the program.
a useful link describing Types and what it means:
http://en.wikipedia.org/wiki/Type_system
If you have ever done much with PHP you will notice that when you declare a varialbe, you do not have to say whether it is an INT or a STRING. However, sometimes you know that you will be receiving a string, but need an int, so you can still type cast variables at runtime, even though when you declared the variable you did not explicitly state the variable would hold an int.
<?php
#some more code here.....
# over here $myValue could be of some different type, but it can dynamically change to another type
$myValue = '5'; #storing a string...so $myValue is currently of type String
$myNewValue = (int)$myValue + 5 #type casted to integer, so in this case $myValue is currently of type integer
?>
If that doesn't help, maybe take a look at this.
myPythonVariable = "I am currently a string" #the variable is of type string
myPythonVariable = 5 #the variable is now of type integer
In the above code sample, myPythonVariable always has a type, whether or not that type changes doesn't matter.

calling bash script generates error on if statement and variable assignment

I'm trying to execute a very simple program (round numbers to lowest integer divisible by 15) but am getting an error:
$min = date +"%M";
if [ $min%15 != 0 ]
then
$min - $min%1
fi
echo $min;
I call it with sh cache.sh
I feel I've followed the syntax I've learned here but I'm getting line 9: syntax error: unexpected end of file What have I got wrong here?
That script is not valid bash syntax. I would start by finding some working examples, and perhaps an entire tutorial. You might start with William Shotts' book, which is available online.
Some notes about your attempt:
The $ is used to request replacement of a variable1 by its value. It is not a sigil that is part of the variable name, as it is in Perl or PHP. So it is not used on the left-hand-side of an assignment.
The shell is primarily used to run other executables, and interprets everything through that lens. If a command line looks like an invocation of another program, the shell will try to run that other program, rather than do anything shell-scripty. Therefore, the command min = date +"%M" will cause the shell to look for a program named min and execute it with three command-line arguments: =, date, and +%M.
In order for an assignment to be recognized as such, there cannot be any space around the =.
Without spaces, min=date +"%M" is still not right, however. The shell will just temporarily assign the literal string "date" to the variable min and then try to run a command called +%M.
If a value has spaces in it, you need quotation marks around it2.
Even with quotes, however,min="date +%M" would assign to min the literal string "date +%M". If you actually want to run the command date +"%M" and use its output as a value, then you have to request that using the command-substitution syntax, $(...). Here our friend the dollar sign is again requesting replacement by a dynamic value, but the parentheses make it a different type of request; instead of a variable's value, the expression is replaced by the output of a command.
Because of the parsing issues noted above, the built-in arithmetic operations only work in certain contexts. Two ways to create a valid arithmetic context are the ((...)) special forms and the let command.
Finally, even if your script were syntactically valid, it is semantically incorrect if your goal is to round down to the nearest multiple of 15. The remainder after dividing by 1 is always zero, so your script ends by attempting to subtract 0 from min - and does nothing with the result anyway, since there's no assignment back to min. If you want to round down, you have to actually subtract the remainder that you just tested. You could do it like this:
min=$(date +%M)
let rem=min%15
if (( rem != 0 )); then
let min-=rem
fi
echo $min
But you could also do it a bit more succinctly:
echo $(( min=$(date +%M), min-=min%15 ))
This works without an if because subtracting 0 is harmless. The comma just lets us put two expressions inside a single set of ((...)). The second expression min-=min%15 is a modifying assignment - it means the same thing as min=min-min%15, but saves us one instance of typing out "min". Putting our friend the replacement-requesting $ in front of ((...)) causes the whole expression to be replaced by its value, so that echo gets something to print out. The value of a list of expressions is the value of the last expression, and the value of an assignment is the same as the value that was assigned, so the result that is echoed is the same as the final value of $min: the closest multiple of 15 minutes after the hour.
1 In shell terminology, variables are actually called "parameters". Just something to bear in mind when reading documentation.
2 You actually don't need quotation marks around the %M in your command for this reason. Everything in the shell is automatically a string; you don't need the quotes to make it one. However, they don't hurt, and putting quotation marks around things is a good habit to have, since it keeps your code from being broken by unexpected special characters in input values.
Your script has many syntax issues. In shell assignment is is
var='val'
instead of
$var='val'
Also there is no space around =
Your correct script can be:
min=$(date +"%M")
if (( min % 15 != 0 ))
then
echo "not fully divisible by 15"
fi
echo $min
min=`date +"%M"`;
if [ $min%15 != 0 ]
then
min=$((min - min%1))
fi
echo $min;
It looks like you converted this from some other language. Here's a working bash version.
#!/bin/bash
min=$(date +"%M")
if [ $(($min % 15)) != 0 ] ; then
min=$(( min - min % 1 ))
fi
echo $min;
local output:
~/tmp › sh ./test.sh
34

Resources