in reply to Re: Re: Hashes and Arrays
in thread Hashes and Arrays

btw, $printrows 0,3 gives the value of what I think should have gone into $printrows 1,1 -- value2. That is what I meant by everything being added to 0 rather than X.

Replies are listed 'Best First'.
Re: Re: Hashes and Arrays
by cees (Curate) on Jul 16, 2003 at 06:18 UTC

    You are talking about a hash of arrays in your original question, but it looks like you really want an array of arrays... Is this correct?

    In your code you have the following:

    push (@{%newhash->{$rows[0]}}, @newrows); push (@{%newhash->{$rows[0]}}, @newrows);

    We can simplify this to the following since $rows[0] = 'IP' and does not change (Do you maybe want a real IP address here?):

    push @{$newhash{IP}}, @newrows); push @{$newhash{IP}}, @newrows);

    Which is essentially saying that you want to treat the value at $newhash{IP} as an array reference, and you want to push the values in @newrows onto the end that array.

    If you want this to be a two dimensional array, then you need to take Paladin's advice and push a reference to the array instead of pushing the values of the array.

    push @{$newhash{IP}}, [@newrows]); push @{$newhash{IP}}, [@newrows]);

    That will make copies of the array, and push a reference to the new array (you could also use \@newrows). Using Data::Dumper, the above will show up as:

    $VAR1 = { 'IP' => [ [ 'value1', 'value2' ], [ 'value1', 'value2' ] ] };

    Is this what you are after?

    Now the loop at the end where you are trying to read the values will require some changes as well:

    @printrows = $newhash{$key}; # wrong -> the hash will contain a refere +nce to an array @printrows = @{$newhash{$key}}; # right -> de-reference the array firs +t
    After those changes, your code prints what you seem to be asking for. Although I am still not 100% sure this is what you are really after...

    - Cees