如果fetchrow_array没有返回任何行,如何将数组赋值为default

时间:2016-08-05 15:55:05

标签: arrays perl

我想我可以把它分成两个问题。

1.如果我想在一步中做一些事情,那该怎么办。

if($sth->fetchrow_array is empty /undef){
    @parent = @default;
}

我尝试过这样的事情,但失败了。

@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是示例代码。为什么我在第二个输出中得到标量值?

@default = (2,3,4);

## First output
@parent = $sth->fetchrow_array or @default;
print @parent;

##Second output;
@parent = $sth->fetchrow_array || @default;
print @parent;

3 个答案:

答案 0 :(得分:4)

而不是fetchrow_array我建议您使用fetchrow_arrayref,如果没有更多数据要返回,则返回undef

然后你可以写

@parent = @{ $sth->fetchrow_arrayref || \@default };

或者,如果方便的话,您可以将结果作为参考保存

$parent = $sth->fetchrow_arrayref || \@default;

答案 1 :(得分:1)

@parent = $sth->fetchrow_array or @default;解析为(@parent = $sth->fetchrow_array) or @default;,它会给你这个警告:

Useless use of private array in void context at foo.pl line 123.

@parent = $sth->fetchrow_array || @default;解析为@parent = ($sth->fetchrow_array || @default);,这更好。但是||将其左操作数置于标量上下文中(因为它需要将其作为布尔值检查)并且它不会两次计算其左操作数。所以它最终与@parent = scalar($sth->fetchrow_array) || @default;相同,这也不是你想要的。

您可以执行以下操作:

@parent = $sth->fetchrow_array;
@parent = @default if !@parent;

但是在一个声明中没有好办法。

答案 2 :(得分:0)

@parent = $sth->fetchrow_array  or  @parent = @default;
(@parent = $sth->fetchrow_array) || (@parent = @default);
@parent = @default unless @parent = $sth->fetchrow_array;

(如果@Shahid Siddique是正确的,fetchrow_array可以在查询没有结果的情况下返回带有一个undef元素的数组,但这还不是你想要的我的经历)