Cody Pendant has asked for the wisdom of the Perl Monks concerning the following question:
I was struggling today with some code where the best structure, I thought, was a hash of arrays.
I read the fine manual, or rather the Perl CD Bookshelf. I know how to do it now, see below, but I found myself asking why, even when I knew how to do it.
Here's an example:
$, = ','; # I like to print out array items this way @my_array = ('Angel','Buffy','Cordelia'); # Now I have an array with three items. I want # to make it be a value in a hash. $my_hash{'my_key'} = [@my_array]; # Turns out to be the correct way to put an array into # a hash value. # But why? Why not # ($my_hash{'my_key'}) = @my_array; # for instance? That was my first thought, array context # on the left hand side comes from brackets -- or # $my_hash{'my_key'} = \@my_array; # is something else that occurred to me that didn't work. # Now I want to push something onto the end of the # array in the value: push (@{$my_hash{'my_key'}},'Darla'); # is the right way to do it, but first I tried just # a regular push, like: # push ($my_hash{'my_key'},'Darla'); # after all, Perl "knows" that value is an array, # but this doesn't work! It tells me "Type of # arg 1 to push must be array (not hash elem)"! # Now I want to get my array back out again, I have to # do this: print @{$my_hash{'my_key'}}; # in order to make it come out as an array and # not as "ARRAY(0x35fd724)". But why?
As you can tell, I'm very much self-taught, but what's obvious to me is that I've missed something about the syntax that led me up a few wrong paths. I had instincts which turned out to be wrong, and the correct syntax took me by surprise. I would never have guessed it.
Can anyone explain why, for instance square brackets on the right hand side mean "array context" in this case, not round brackets on the left hand side? And why an array comes out as "ARRAY(0x35fd724)" -- "I know it's an array, but I'm not giving it to you!" until I learnt the, to me quite baffling, syntax of "at-symbol, curly brackets, hash reference, close curly brackets"?
Thanks in advance.
--
($_='jjjuuusssttt annootthhrer pppeeerrrlll haaaccckkeer')=~y/a-z//s;print;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: My Struggles with Hash-of-Arrays Syntax
by shotgunefx (Parson) on Apr 19, 2002 at 09:25 UTC | |
|
Re: My Struggles with Hash-of-Arrays Syntax
by Hofmator (Curate) on Apr 19, 2002 at 09:11 UTC | |
by Dog and Pony (Priest) on Apr 19, 2002 at 09:33 UTC | |
|
Re: My Struggles with Hash-of-Arrays Syntax
by Ryszard (Priest) on Apr 19, 2002 at 09:42 UTC | |
|
Re: My Struggles with Hash-of-Arrays Syntax
by Cody Pendant (Prior) on Apr 20, 2002 at 00:08 UTC |