in reply to Ternary operator can't be used as first argument of push
"In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable). If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken...
...Assigning to the whole array @_ removes that aliasing, and does not update any arguments"
So, to do what you are attempting (which I personally feel is poor programming style), you need to manually vivify the elements you want updated, and you need to fill them one element at at time (cannot use array assignment).
The code segment below illustrates this:
# MODIFIED Second example; nothing gets assigned to @array1 or @array2 + the first time, but DOES the second time # But no compiletime errors are generated either: my $condition = int rand 2; sub testthis { my $i=0; # Note: assignment is element-by-element foreach $word( qw/This that and the other/){ $_[$i] = $word; $i++; } } my ( @array1, @array2 ); testthis( $condition ? @array1 : @array2 ); print "With Empty arrays setting $condition: @array1,\n @array +2;\n"; @array1 = qw/no longer empty one/; @array2 = qw/no longer empty two/; testthis( $condition ? @array1 : @array2 ); print "With NON-Empty arrays setting $condition: @array1,\n @a +rray2;\n"; #################################### ## Output ### With Empty arrays setting 0: , ; With NON-Empty arrays setting 0: no longer empty one, This that and the;
Note - only the existing array indices are updated. New ones are NOT created.
|
|---|