Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Hashes... Light switch isn't coming on

by jethro (Monsignor)
on Dec 12, 2012 at 17:35 UTC ( #1008537=note: print w/replies, xml ) Need Help??

in reply to Hashes... Light switch isn't coming on

To supplement the answer by LanX, there are two ways to fill an array or hash: Either you initialize it with all values at once or you insert values one at a time. You seem to mix up these two methods. Here is how both work for arrays and hashes:

# initialize an array at once with 3 scalars, two array pointers and o +ne hash pointer: @array= (1,2,3,\@anotherarray,[1,2],{1=>15}); # initialize a hash at once with three keys. Data is one scalar, one h +ash pointer and one array pointer %hash= (1=>15, 7=>{5=>4}, 2=>[1,2,3]);

As you can see initializing at once is not complicated, you just have to remember that hash and array are both initialized with an array constant that uses (), but constant array pointers are specified with [] and constant hash pointers are specified with {}. Also any old values are completely erased so this doesn't work when you want to add values one by one

Inserting values one at a time (mostly in a loop) on the other hand uses the same "interface" as any normal array or hash operation, so:

foreach ... { $array[$i][$j]= $value; # or push( @{$array[$i]}, $value); $hash{$i}{$j}= $value; }

Since only one value inside the array or hash is changed or added and all other values remain, this works very well in a loop

Replies are listed 'Best First'.
Re^2: Hashes... Light switch isn't coming on
by muba (Priest) on Dec 12, 2012 at 18:22 UTC

    Note that a pointer is not the same as a reference. A pointer points to a memory location where a value might be stored, whereas a reference —at least in Perl parlance— points to a value.

      Wikipedia says

      While "pointer" has been used to refer to references in general, it more properly applies to data structures whose interface explicitly allows the pointer to be manipulated (arithmetically via pointer arithmetic) as a memory address...

      So, while you are correct that there is a subtle difference between those words, in a language where low-level pointers don't exist it should be obvious that pointer is an alias for reference

      But thanks for the info, I wasn't really aware of the distinction

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1008537]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2017-10-22 03:31 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (272 votes). Check out past polls.