in reply to Getting values in Hash Reference?
Remember that a reference is a scalar, even if the thing it points to isn't. So $hash_ref is a scalar, even though it _points to_ a hash.
You can't take a slice of a scalar. You can take a slice of an array (@foo[2,4,5]), or you can take a slice of a hash (@foo{'a','b','d'}), but a slice of a scalar doesn't make sense.
However, you _can_ take a slice of a hash, so you _can_ take a slice of the hash that the reference points to. What you have to do is dereference it, to get to the hash, and then take the slice of that. There are several syntaxes you can use for this, but here's one:
@{%$hash_ref}{'a', 'b'}Notice that I've used % to dereference, because the thing that the reference points to is a hash. (If it pointed to an array, I would dereference with @ or if it pointed to a scalar I'd use $ to do the dereferencing.) The extra set of braces is just to clarify what it is that I'm slicing with the @ symbol.
update: It turns out that the hash slice notation is enough to dereference the hash reference, so the % isn't necessary (although it doesn't hurt anything), so the above could also be written thusly:
@{$hash_ref}{'a', 'b'}However, in general, you would dereference a hash with % thusly:
%$hash_refAlso note that if you want to pull out just a certain hash value, you would dereference with a scalar $ sigil, thusly:
$$hash_ref{$key}If you need to use more complex syntax to refer to the hash reference, you then need the clarifying braces (like we used above with the slice):
It is also possible to dereference with the -> arrow notation, but in that case everything on the left side of the arrow has to evaluate to a reference, which is then dereferenced and the operation on the right (usually subscripting) is performed on the result. So in your code, @hash_ref would need, by itself, to be a reference, but it's not; it's an array (which does not happen to be defined). So you need to put the reference on the left side of the arrow:
$hash_ref->Then on the right side you put your operation, such as subscripting.
$hash_ref->{foo}However, since braces in this case would normally mean ordinary hash subscripting, not slicing, this notation does not work for hash slicing.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Getting values in Hash Reference?
by Anonymous Monk on Apr 24, 2006 at 13:53 UTC | |
by jonadab (Parson) on Apr 25, 2006 at 11:30 UTC | |
by abuomarm (Initiate) on Sep 03, 2013 at 22:40 UTC | |
by Anonymous Monk on Sep 07, 2017 at 09:46 UTC |