Home > Archive > PERL Beginners > January 2006 > return values evaluating to true
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
return values evaluating to true
|
|
| Radhika 2006-01-25, 6:57 pm |
| Hi,
I have a snippet of code as below.
Even when I return 0 or '', why does @blocks evaluate to true?
If rows returned are 0, then if(@blocks) should evaluate to false, correct?
Thanks,
Radhika
---
use strict;
use diagnostics;
my @blocks = ();
sub do_something
{
my @row = @_;
return @row if(@row);
return '';
}
@blocks = do_something();
if(!@blocks)
{
print("Got this number: @blocks\n");
}
else
{
print("Got nothing\n");
}
--
It is all a matter of perspective. You choose your view by choosing where
to stand.
Larry Wall
---
| |
| Chas Owens 2006-01-25, 6:57 pm |
| On 1/25/06, radhika <radhika@88thstreet.com> wrote:
> Hi,
> I have a snippet of code as below.
> Even when I return 0 or '', why does @blocks evaluate to true?
> If rows returned are 0, then if(@blocks) should evaluate to false, correc=
t?
> Thanks,
> Radhika
> ---
> use strict;
> use diagnostics;
> my @blocks =3D ();
> sub do_something
> {
> my @row =3D @_;
> return @row if(@row);
> return '';
> }
> @blocks =3D do_something();
> if(!@blocks)
> {
> print("Got this number: @blocks\n");
> }
> else
> {
> print("Got nothing\n");
> }
snip
The second return in do_something() is your problem.
| |
| Bob Showalter 2006-01-25, 6:57 pm |
| radhika wrote:
> Hi,
> I have a snippet of code as below.
> Even when I return 0 or '', why does @blocks evaluate to true?
> If rows returned are 0, then if(@blocks) should evaluate to false, correct?
> ...
> sub do_something
> {
> my @row = @_;
> return @row if(@row);
> return '';
> }
> @blocks = do_something();
> if(!@blocks)
When you return '', the @blocks array contains a single element with the
value ''. When you test an array with if(), you're evaluating the
array in scalar context, which returns the number of elements.
So "if(!@blocks)" is saying "if the @blocks array doesn't contain any
elements...". But it *does* contain the single '' element.
Your solution is to use:
return ();
or just
return;
This will cause @blocks to receive an empty list and your test will work
as you intend.
|
|
|
|
|