Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally push to 1 of 2 arrays in Perl

Tags:

perl

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;"
like image 615
jeberle Avatar asked Jan 21 '13 19:01

jeberle


People also ask

What does Unshift do in Perl?

unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.

What is dynamic array in Perl?

Perl arrays are dynamic in length, which means that elements can be added to and removed from the array as required. Perl provides four functions for this: shift, unshift, push and pop. shift removes and returns the first element from the array, reducing the array length by 1.


3 Answers

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;
like image 51
ysth Avatar answered Sep 19 '22 05:09

ysth


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.

like image 45
melpomene Avatar answered Sep 19 '22 05:09

melpomene


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!

like image 26
robert_b_clarke Avatar answered Sep 21 '22 05:09

robert_b_clarke