perl

$ and % operator being used in conjunction


I've been given some code to look at and "solve".

foreach $field (keys %$exam)

The code above is the area I’m having difficulty in understanding. I thought $ was scalar and % was a hash, so what is %$?


Solution

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