Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push to array reference

Is it possible to push to an array reference in Perl? Googling has suggested I deference the array first, but this doesn't really work. It pushes to the deferenced array, not the referenced array.

For example,

my @a = ();  my $a_ref = [@a];  push(@$a_ref,"hello");  print $a[0]; 

@a will not be updated and this code will fail because the array is still empty

(I'm still learning Perl references, so this might be an incredibly simple question. Sorry if so)

like image 940
Mike Avatar asked Jun 16 '10 15:06

Mike


People also ask

How do you push to an array?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

How do you push an object to an array without references?

The only way you can address your issue is to pass the clone of the object you want to push into the vector. In such cases normally you would write a clone() method to your object that returns a deep copy of itself. The object returned by this method can be pushed to the array.

Can we push array into array?

Adding Array into the Array using push() push() method. The push() function allows us to push an array into an array. We can add an array into an array, just like adding an element into the Array.

Does array push copy?

Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy. So, since objects are not copied in any way, there's no deep or shallow copy for them.


1 Answers

It might help to think in terms of memory addresses instead of variable names.

my @a = ();       # Set aside memory address 123 for a list.  my $a_ref = [@a]; # Square brackets set aside memory address 456.                   # @a COPIES the stuff from address 123 to 456.  push(@$a_ref,"hello"); # Push a string into address 456.  print $a[0]; # Print address 123. 

The string went into a different memory location.

Instead, point the $a_ref variable to the memory location of list @a. push affects memory location 123. Since @a also refers to memory location 123, its value also changes.

my $a_ref = \@a;       # Point $a_ref to address 123.  push(@$a_ref,"hello"); # Push a string into address 123. print $a[0];           # Print address 123. 
like image 169
Robert Wohlfarth Avatar answered Sep 29 '22 08:09

Robert Wohlfarth