Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by jethro (Monsignor)
on Dec 12, 2012 at 17:35 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1008537]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-25 17:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found