Reputation: 758
Is there a better way to do this? I'm trying to build 2 arrays based on the value of a scalar:
my (@x, @y);
my $r = [$v1, $v2, $v3];
push @x, $r if $s eq 'YES';
push @y, $r if $s ne 'YES';
I tried using:
push $s eq 'YES' ? @x : @y, $r;
with and without parens, but no go.
Error is:
Type of arg 1 to push must be array (not null operation) at comp_report.pl line 79, near "$r;"
Upvotes: 6
Views: 1246
Reputation: 1513
My preferred solution would be
if($s eq 'YES'){
push @x, $r;
else{
push @y, $r;
}
Just a style thing. Using a ternary expression as the first argument to push looks messy to me, and I don't mind the extra lines. Personal taste I guess!
Upvotes: 1
Reputation: 98528
push requires its first parameter to be an actual array (at least before perl 5.14 and earlier - it may have changed), not an expression, so you need to:
push @{ $s eq 'YES' ? \@x : \@y}, $r;
Beginning in 5.14, builtins such as push experimentally can take arbitrary hard references, so this works:
push $s eq 'YES' ? \@x : \@y, $r;
Upvotes: 13
Reputation: 85907
push @{ $s eq 'YES' ? \@x : \@y }, $r;
push
really wants to get an array as its first argument, but you can still select the target dynamically by using references.
Upvotes: 9