Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ and % operator being used in conjunction

Tags:

perl

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.

like image 354
andrew Patterson Avatar asked Dec 03 '22 00:12

andrew Patterson


2 Answers

%$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}.

like image 50
ArtMat Avatar answered Jan 13 '23 12:01

ArtMat


$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;}

like image 28
edem Avatar answered Jan 13 '23 13:01

edem