Link to home
Start Free TrialLog in
Avatar of mdigiova
mdigiova

asked on

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?

Thanks!
Avatar of ozo
ozo
Flag of United States of America image

$site_version{$site_array->{name}} = [@{$site_array->{array}}];
push @{$site_array->{array}},$newelement;
Avatar of prakashk021799
prakashk021799

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.
Avatar of mdigiova

ASKER

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!
ASKER CERTIFIED SOLUTION
Avatar of prakashk021799
prakashk021799

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks prakashks!