Reputation: 459
I guess I can divide it into two questions.
1.What if I want to do something below in one single step.
if($sth->fetchrow_array is empty /undef){
@parent = @default;
}
I tried something like this but failed.
@parent = $sth->fetchrow_array or @default;
## Problem is it assign undef if array1 is undef.
@parent = $sth->fetchrow_array || @default;
## problem is it assign scalar value to the parent if it's not undef
2.Below is the sample code. Why I get scalar value in second output?
@default = (2,3,4);
## First output
@parent = $sth->fetchrow_array or @default;
print @parent;
##Second output;
@parent = $sth->fetchrow_array || @default;
print @parent;
Upvotes: 2
Views: 616
Reputation: 126722
Instead of fetchrow_array
I suggest that you use fetchrow_arrayref
, which returns undef
if there is no more data to be returned
Then you can write
@parent = @{ $sth->fetchrow_arrayref || \@default };
or, if it's convenient, you could keep the result as a reference with
$parent = $sth->fetchrow_arrayref || \@default;
Upvotes: 4
Reputation: 118605
@parent = $sth->fetchrow_array or @parent = @default;
(@parent = $sth->fetchrow_array) || (@parent = @default);
@parent = @default unless @parent = $sth->fetchrow_array;
(this won't quite do what you want if @Shahid Siddique is correct that fetchrow_array
can return an array with one undef
element when the query has no results, but that hasn't been my experience)
Upvotes: 0
Reputation: 85767
@parent = $sth->fetchrow_array or @default;
parses as (@parent = $sth->fetchrow_array) or @default;
, which should give you this warning:
Useless use of private array in void context at foo.pl line 123.
@parent = $sth->fetchrow_array || @default;
parses as @parent = ($sth->fetchrow_array || @default);
, which is better. But ||
puts its left operand in scalar context (because it needs to check it as a boolean value) and it doesn't evaluate its left operand twice. So it ends up being the same as @parent = scalar($sth->fetchrow_array) || @default;
, which is also not what you want.
You can do the following:
@parent = $sth->fetchrow_array;
@parent = @default if !@parent;
But there's no good way to do it in one statement.
Upvotes: 1