What is it called when an assignment contains conditionals that fall through to be assigned as the value of the variable? - assignment-operator

I know that this is simple terminology, but I can't get it via google searching... what is it called when the value of a variable being assigned passes through?
An example in php:
<?php
if($bob = 5){ echo 'The assignment came through as a truthy value!, bob now equals '.$bob.'!'; }
if($bob = false){ echo 'The assignment occurred again, but the value of the assignment is the value "false", so this if block will not be executed!. Bob now equals '.$bob.'!'; }
echo ' Finally, bob is a: '.(string) $bob;
?>
An example in javascript:
bob = bob || {};

In your first example, you're using assignment as an expression; that is, the assignment statement returns the value assigned (this behavior is a common source of bugs; often people accidentally use = instead of == in their condition).
The second example is using the short-circuiting behavior of the || operator.

Related

Perl `defined`function complexity

I have a perl script, which is accepting a list of arguments(mandatory and non-mandatory). Based on these args flow of script is determined. Where i am confused is, if the arg(which is in the form of switch) is used multiple times in the script to determine flow(most of the time used in if loop), then which one is better
if(defined arg){}
OR
my $switch = defined arg ? 1:0; if($switch){}
defined already returns true or false. Using the result of defined to select a true value for true case and a false value for the false case is just extra work. This does all the work you need and no extra work:
if( defined $foo ) { ... }
Sometimes I want to print that true or false value, so I'll use the double bang (negate, and negate again) to normalize the value:
!! defined $foo

Decision in Inspec profiles

I'm running a postgres inspec profile and would like to run certain tests only if the node is a master node. Here is my profile
sql = postgres_session('postgres', password, 'localhost')
result = describe sql.query('SELECT pg_is_in_recovery()') do
its('output') { should eq 'f' }
end
if result == 'f'
describe sql.query('SELECT state from pg_stat_replication') do
its('output') { should match 'streaming' }
end
end
But this doesn't work as the variable result doesn't store value 'f'.
My question is how do i store a value in a variable and use that for the next test in inspec ?
How do we print variable values in inspec (debug statements)
speaking only from my memory, you should assign the sql query into a variable, pass that variable to the describe block so you could use the matcher (but it feels that you do not need it in your case), and then place a condition on that variable. it should be something like:
sql = postgres_session('postgres', password, 'localhost')
result = sql.query('SELECT pg_is_in_recovery()')
if result.output == 'f'
describe sql.query('SELECT state from pg_stat_replication') do
its('output') { should match 'streaming' }
end
end

MATLAB assign variable name

I have a variable called 'int' with alot of data in it. I would like to find a way to programically rename this variable with a user input. So I can query the user indentifcation information about the data, say the response is 'AA1', I want either rename the variable 'int' to 'AA1' or make 'AA1' a variable that is identical to int.
A problem using the input command arises because it allows the user to assign a value to an already created varialbe, instead of actually creating a variable name. Would using the eval function, or a variation of it, help me achieve this? Or is there an easier way?
Thanks!
Just for the record, int is a rather poor variable name choice.
That aside, you can do what you want as follows
say foo is the variable that holds a string that the user input. You can do the following:
% eliminate leading/trailing whitespace
foo = strtrim(foo);
a = regexp('[a-zA-Z][a-zA-Z0-9_]*',foo));
if numel(a) == 0
fprintf('Sorry, %s is not a valid variable name in matlab\n', foo);
elseif a ~= 1
fprintf('Sorry, %s is not a valid variable name in matlab\n', foo);
elseif 2 == exist(foo,'var')
fprintf('Sorry, %s already in use as a variable name.');
else
eval([foo,' = int']);
end
Assuming int (and now foo) is a structure with field named bar, you can read bar as follows:
barVal = eval([foo,'.bar']);
This is all somewhat clunky.
An alternative approach, that is far less clunky is to use an associative array, and let the user store various values of int in the array. The Matlab approach for associative arrays is Maps. That would be my preferred approach to this problem. Here is an example using the same variables as above.
nameValueMap = containers.Map;
nameValueMap(foo) = int;
The above creates the association between the name stored in foo with the data in the variable int.
To get at the data, you just do the following:
intValue = nameValueMap(foo);

How can I assign a boolean condition result to a scalar variable in perl?

I am doing the following, but it is not working properly:
my $enabled = $hash &&
$hash->{'key'} &&
$hash->{'key'}->{'enabled'} &&
$hash->{'key'}->{'active'};
Is this an acceptable way to assign a boolean value to a scalar variable?
My code is misbehaving in strange ways, as it is, and I believe it is because of this assignment. I have validated that the individual values exist for all of these keys and are set to a value.
P.S. Sorry for being a noob! I googled for ~10 minutes and couldn't find the answer anywhere.
The Perl boolean operators like &&, ||, and, or don't return a boolean value, they return the value of one of their arguments:
say 2 && 3;
outputs 3.
You can force it to a boolean with the double negation trick:
say !!(2 && 3);
# or
say not not 2 && 3;
outputs 1.

How can I set a default value for a Perl variable?

I am completely new to Perl. I needed to use an external module HTTP::BrowserDetect. I was testing some code and tried to get the name of the OS from os_string method. So, I simply initialized the object and created a variable to store the value returned.
my $ua = HTTP::BrowserDetect->new($user_agent);
my $os_name = $ua->os_string();
print "$user_agent $os_name\n";
there are some user agents that are not browser user agents so they won't get any value from os_string. I am getting an error Use of uninitialized value $os_name in concatenation (.) or string
How do I handle such cases when the $os_name is not initialized because the method os_string returns undef (this is what I think happens from reading the module source code). I guess there should be a way to give a default string, e.g. No OS in these cases.
Please note: the original answer's approach ( $var = EXPRESSION || $default_value ) would produce the default value for ANY "Perl false values" returned from the expression, e.g. if the expression is an empty string, you will use the default value instead.
In your particular example it's probably the right thing to do (OS name should not be an empty string), but in general case, it can be a bug, if what you actually wanted was to only use the default value instead of undef.
If you only want to avoid undef values, but not empty string or zeros, you can do:
Perl 5.10 and later: use the "defined-or operator" (//):
my $os_name = $ua->os_string() // 'No OS';
Perl 5.8 and earlier: use a conditional operator because defined-or was not yet available:
my $os_string = $ua->os_string(); # Cache the value to optimize a bit
my $os_name = (defined $os_string) ? $os_string : 'No OS';
# ... or, un-optimized version (sometimes more readable but rarely)
my $os_name = (defined $ua->os_string()) ? $ua->os_string() : 'No OS';
A lot more in-depth look at the topic (including details about //) are in brian d foy's post here: http://www.effectiveperlprogramming.com/2010/10/set-default-values-with-the-defined-or-operator/
my $os_name = $ua->os_string() || 'No OS';
If $ua->os_string() is falsy (ie: undef, zero, or the empty string), then the second part of the || expression will be evaluated (and will be the value of the expression).
Are you looking for defined?