I'm busy learning Perl at the moment and I've been given some code to look at and "solve".
foreach $field (keys %$exam)
The code above is the area Im having difficulty in understanding. I thought $ was scalar and % was a hash and so I'm unsure what %$ is.
Any help appreciated!
Thanks guys.
%$exam
says that you are using not a normal hash, but a dereferenced one, i.e. somewhere before this statement $exam
became the reference of a hash (for example $exam = \%somehash
or $exam = { a => 1 }
for an anonymous hashref). Now, in order to use the previously referenced hash you have to use this syntax to dereference it. To use it unambiguously, it could be written as %{$exam}
.
$exam = {a=>1, b=>2}; # anonym hash, $exam is ref for this hash
In order to use this ref like hash you have to use dereferencing operator %
before ref
foreach $field (keys %$exam)
For example the same for array ref.
$a = [1,2,3,4]; # anonym arr, $a is ref for this array
So that you have to use operator @
before ref $a for dereferencing
foreach $element (@$a) {print $element;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With