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;"
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.
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.
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;
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With