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
I'm new to programming and writing my first function for MATLAB. The name of the function should be "picalc".
The purpose is to accept an "x" and "y" value as input arguments. These values must be plugged into x^2+y^2, and if this result is less than or equal to 1, return true. Otherwise, return false.
Here is what I have so far:
function[true,false]=picalc(x,y);
if x^2+y^2<=1
return true
else
return false
end
Can anyone tell me why this won't work? As it stands, I get the following error:
Error: File: picalc.m Line: 6 Column: 13
Unexpected MATLAB expression.
Thank you very much for your expertise!
In MATLAB, return does not return value as an output of a function call but rather returns control to the invoking function (see documentation here). As such, it does not take argument, because what it does is merely redirecting the flow of the program to the function/statement that invokes the function/statement containing the return statement.
Your function should be written like this:
function result = picalc(x,y);
if x^2+y^2<=1
result = true;
else
result = false;
end
The variable on left hand side of the function declaration is the output variable. By assigning value to this valuable, you are "returning" an output.
There is some misunderstanding between me and Scala
0 or 1?
object Fun extends App {
def foo(list:List[Int], count:Int = 0): Int = {
if (list.isEmpty) { // when this is true
return 1 // and we are about to return 1, the code goes to the next line
}
foo(list.tail, count + 1) // I know I do not use "return here" ...
count
}
val result = foo( List(1,2,3) )
println ( result ) // 0
}
Why does it print 0?
Why does recursion work even without "return"
(when it is in the middle of function, but not in the end)?
Why doesn't it return 1? when I use "return" explicitly?
--- EDIT:
It will work if I use return here "return foo(list.tail, count + 1)'.
Bu it does NOT explain (for me) why "return 1" does not work above.
If you read my full explanation below then the answers to your three questions should all be clear, but here's a short, explicit summary for everyone's convenience:
Why does it print 0? This is because the method call was returning count, which had a default value of 0—so it returns 0 and you print 0. If you called it with count=5 then it would print 5 instead. (See the example using println below.)
Why does recursion work even without "return" (when it is in the middle of function, but not in the end)? You're making a recursive call, so the recursion happens, but you weren't returning the result of the recursive call.
Why doesn't it return 1? when I use "return" explicitly? It does, but only in the case when list is empty. If list is non-empty then it returns count instead. (Again, see the example using println below.)
Here's a quote from Programming in Scala by Odersky (the first edition is available online):
The recommended style for methods is in fact to avoid having explicit, and especially multiple, return statements. Instead, think of each method as an expression that yields one value, which is returned. This philosophy will encourage you to make methods quite small, to factor larger methods into multiple smaller ones. On the other hand, design choices depend on the design context, and Scala makes it easy to write methods that have multiple, explicit returns if that's what you desire. [link]
In Scala you very rarely use the return keyword, but instead take advantage that everything in an expression to propagate the return value back up to the top-level expression of the method, and that result is then used as the return value. You can think of return as something more like break or goto, which disrupts the normal control flow and might make your code harder to reason about.
Scala doesn't have statements like Java, but instead everything is an expression, meaning that everything returns a value. That's one of the reasons why Scala has Unit instead of void—because even things that would have been void in Java need to return a value in Scala. Here are a few examples about how expressions work that are relevant to your code:
Things that are expressions in Java act the same in Scala. That means the result of 1+1 is 2, and the result of x.y() is the return value of the method call.
Java has if statements, but Scala has if expressions. This means that the Scala if/else construct acts more like the Java ternary operator. Therefore, if (x) y else z is equivalent to x ? y : z in Java. A lone if like you used is the same as if (x) y else Unit.
A code block in Java is a statement made up of a group of statements, but in Scala it's an expression made up of a group of expressions. A code block's result is the result of the last expression in the block. Therefore, the result of { o.a(); o.b(); o.c() } is whatever o.c() returned. You can make similar constructs with the comma operator in C/C++: (o.a(), o.b(), o.c()). Java doesn't really have anything like this.
The return keyword breaks the normal control flow in an expression, causing the current method to immediately return the given value. You can think of it kind of like throwing an exception, both because it's an exception to the normal control flow, and because (like the throw keyword) the resulting expression has type Nothing. The Nothing type is used to indicate an expression that never returns a value, and thus can essentially be ignored during type inference. Here's simple example showing that return has the result type of Nothing:
def f(x: Int): Int = {
val nothing: Nothing = { return x }
throw new RuntimeException("Can't reach here.")
}
Based on all that, we can look at your method and see what's going on:
def foo(list:List[Int], count:Int = 0): Int = {
// This block (started by the curly brace on the previous line
// is the top-level expression of this method, therefore its result
// will be used as the result/return value of this method.
if (list.isEmpty) {
return 1 // explicit return (yuck)
}
foo(list.tail, count + 1) // recursive call
count // last statement in block is the result
}
Now you should be able to see that count is being used as the result of your method, except in the case when you break the normal control flow by using return. You can see that the return is working because foo(List(), 5) returns 1. In contrast, foo(List(0), 5) returns 5 because it's using the result of the block, count, as the return value. You can see this clearly if you try it:
println(foo(List())) // prints 1 because list is empty
println(foo(List(), 5)) // prints 1 because list is empty
println(foo(List(0))) // prints 0 because count is 0 (default)
println(foo(List(0), 5)) // prints 5 because count is 5
You should restructure your method so that the value that the body is an expression, and the return value is just the result of that expression. It looks like you're trying to write a method that returns the number of items in the list. If that's the case, this is how I'd change it:
def foo(list:List[Int], count:Int = 0): Int = {
if (list.isEmpty) count
else foo(list.tail, count + 1)
}
When written this way, in the base case (list is empty) it returns the current item count, otherwise it returns the result of the recursive call on the list's tail with count+1.
If you really want it to always return 1 you can change it to if (list.isEmpty) 1 instead, and it will always return 1 because the base case will always return 1.
You're returning the value of count from the first call (that is, 0), not the value from the recursive call of foo.
To be more precise, in you code, you don't use the returned value of the recursive call to foo.
Here is how you can fix it:
def foo(list:List[Int], count:Int = 0): Int = {
if (list.isEmpty) {
1
} else {
foo(list.tail, count + 1)
}
}
This way, you get 1.
By the way, don't use return. It doesn't do always what you would expect.
In Scala, a function return implicitly the last value. You don't need to explicitly write return.
Your return works, just not the way you expect because you're ignoring its value. If you were to pass an empty list, you'd get 1 as you expect.
Because you're not passing an empty list, your original code works like this:
foo called with List of 3 elements and count 0 (call this recursion 1)
list is not empty, so we don't get into the block with return
we recursively enter foo, now with 2 elements and count 1 (recursion level 2)
list is not empty, so we don't get into the block with return
we recursively enter foo, now with 1 element and count 2 (recursion level 3)
list is not empty, so we don't get into the block with return
we now enter foo with no elements and count 3 (recursion level 4)
we enter the block with return and return 1
we're back to recursion level 3. The result of the call to foo from which we just came back in neither assigned nor returned, so it's ignored. We proceed to the next line and return count, which is the same value that was passed in, 2
the same thing happens on recursion levels 2 and 1 - we ignore the return value of foo and instead return the original count
the value of count on the recursion level 1 was 0, which is the end result
The fact that you do not have a return in front of foo(list.tail, count + 1) means that, after you return from the recursion, execution is falling through and returning count. Since 0 is passed as a default value for count, once you return from all of the recursed calls, your function is returning the original value of count.
You can see this happening if you add the following println to your code:
def foo(list:List[Int], count:Int = 0): Int = {
if (list.isEmpty) { // when this is true
return 1 // and we are about to return 1, the code goes to the next line
}
foo(list.tail, count + 1) // I know I do not use "return here" ...
println ("returned from foo " + count)
count
}
To fix this you should add a return in front of foo(list.tail.....).
you return count in your program which is a constant and is initialized with 0, so that is what you are returning at the top level of your recursion.
I am using LWP::UserAgent like below
my $ua = LWP::UserAgent->new;
my $response = $ua->request ( ...);
if ( $response->is_success() )
{
...
}
print $response->is_success();
Problem I am facing is that is_success() is returning blank. I was expecting 1 (TRUE) or 0 (FALSE). What am I doing wrong here? Is print statement right?
Not returning anything is correct and usual way in Perl to return false result from function, don't expect literal 0 number when you only need logical false result. Your request is most likely returned with non 2xx or 3xx code.
From the Perl documentation:
The number 0, the strings '0' and "" , the empty list () , and undef
are all false in a boolean context. All other values are true.
Negation of a true value by ! or not returns a special false value.
When evaluated as a string it is treated as "" , but as a number, it
is treated as 0. Most Perl operators that return true or false behave
this way.
In other words, your mistake is assuming that boolean false is always represented by 0. It would be more accurate to say that in Perl false is represented by "empty", with what that means depending on the context.
This is useful, because it allows for clean code in a variety of contexts:
#evaluates false when there are no more lines in the file to process
while (<FILE>) { ... }
#evaluates false when there are no array elements
if (!#array) { ... }
#evaluates false if this variable in your code (being used as a reference)
#hasn't been pointed to anything yet.
unless ($my_reference) { ... }
And so on...
In your case, it's not clear why you want false to be equal to zero. The if() statement in your code should work as written. If you need the result to be explicitly numeric for some reason, you could do something like this:
my $numeric_true_false = ($response->is_success() ? 1 : 0);
From the discussion in comments:
$response->status_line
actually returned 500 Can't Connect to database.
With $response->is_success(), I was unable to understand the response from db.
Used $response->status_line to find out exactly where the code was failing.
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?