• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 166
  • Last Modified:

adding to an element to an array

Hi all,

I have created the following:
$site_array->{name} = $current_hash[0];
                    $site_array->{different} = false;
                    $site_array->{array} = [$current_hash[3]];
                    $site_version{$site_array->{name}} = $site_array;

Basically, what I'm trying to do is to have a hash pointing to an array and some scalar variables.  This seems to work when I first create it.  However, I want to push new elements onto the array later on in the program.  I've tried to do this, but what ends up happening is all the hashes end up pointing to the same array.  I want to keep all the arrays distinct.  Basically, I think this is a problem of scope.  Can someone please give me a hand?

  • 2
  • 2
1 Solution
$site_version{$site_array->{name}} = [@{$site_array->{array}}];
push @{$site_array->{array}},$newelement;
use 'my' variables in the current scope.

For example:

my $hash;
for ('a'..'z') {
   my @array = (rand(100)) x 10;  # fill the array with 10 random elements
   $hash->{$_} = \@array;  # save the array ref in hash

The array is created afresh in each iteration. At the end of the loop you will have 26 elements in $hash, each pointing to a different array.
mdigiovaAuthor Commented:
Thanks for the answers, but I don't think it's what I need.  prakashk, I tried using "my" previously, but I ran into the same problem.  Is it possible I'm not using it correctly?  Here's the code I was trying:

my @temp_array = @{$site_version{$current_hash[0]}{array}};
push @temp_array, $current_hash[3];
@{$site_version{$current_hash[0]}{array}} = @temp_array

The array is already created, but later on, I want to add an element, so I'm trying to access the old array, push in a new value, then set it back, but it isn't working properly.  Any ideas?  Also, ozo, I create a bunch of hashes pointing to arrays initially so I don't think that I can use @{$site_array->{array} because it's only pointing to the array of the last hash that I've created.  If I want to add to an array in a previously created hash how would I do it?

Thanks again!
For adding an element, you don't need to create a temp array.

push @{$site_version{$current_hash[0]}{array}}, $current_hash[3];

this should do it.

mdigiovaAuthor Commented:
Thanks prakashks!

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now