in reply to saving nested arrays in a hash

There are a a lot of bugs in your example code. Please add 'use warnings;' at the beginning, you will find out that a lot of errors get noticed that way. Also 'use strict;' is advisable

To answer your question, the problem is that your array references always point to the same data structure. The reason is that you use global variables. To correct that you could either use 'my' to create a new variable every time, i.e. my @array1= ();, or you could make sure that you copy the values, i.e. $hash{$_} = [ [@array1], ... ];

But your script has more problems than that. For example:

$array1=();. The $ should be a @, if you had warnings on, perl would have told you

array1_ref = \@array1;. A '$' is missing in front of the array1_ref. Again perl would have told you with warnings on

Also the clearing of @array1 and @array2 should be before the while loop, if I get your intention right

You could add a line 'use Data::Dumper;' to the beginning of your program and then for example print Dumper(\%hash); at the end to find out how the data structure looks in reality. Data::Dumper ist the best available debugging tool you can find in perl on short notice ;-)

Replies are listed 'Best First'.
Re^2: saving nested arrays in a hash
by maayanster (Initiate) on Aug 26, 2010 at 16:33 UTC
    thanks! it works now. so what's the technical difference between $ref=\@something and $ref =[@something] ? sorry about the faulty example code... it's not copied from the actual script.. I just typed it here with the silly mistakes included

    my bad.

    :)

      Lets say @something is at memory location 0x12345

      $ref= \@something; print $ref; # would print 0x12345, right? $ref2= \@something; print $ref2; # would print 0x12345 as well

      Obvious, right? You take a reference to the array, it will be always the same. Now the other case:

      $ref= [ @something ]; # would be the same as $ref= \( @something ); # if that syntax where possible, or my @x= ( @something ); # with correct syntax $ref= \@x;

      i.e. [] is just () with an additional reference-taking. And by doing ( @array ) you are creating a new array (at a new memory address) with the contents of @array filled in

      ( @array ) is not the same as @array. This is obvious when you look at @newarray= ( @array1, @array2 );. It can't be the same

      $ref1 = \@arr; $ref2 = \@arr;

      The two references both point to the same underlying data structure.

      $ref1 = [ @arr ]; $ref2 = [ @arr ];

      The two references each point to different anonymous arrays, which have the same values as @arr, but are different structures.

      As Occam said: Entia non sunt multiplicanda praeter necessitatem.