1

Why does dereferencing a hash reference into hash & assigning it to a scalar gives an irrelevant value (at least to me)?

Code:

my $hash = {
        1 => 9,
        2 => 10,
        3 => 11,
        4 => 12,
        5 => 13,
        6 => 14,
        7 => 15,
        8 => 16,
       };

my $dereferenced = %$hash;

print $dereferenced;

Perl version : 5.12.4

OS : Windows 7

The value printed is

7/16

Whether it has something to do with Perl internals?

Wolf
  • 9,679
  • 7
  • 62
  • 108
InnovWelt
  • 660
  • 1
  • 8
  • 21
  • 1
    What would you expect `$dereferenced` to contain? – Borodin Jan 23 '14 at 07:40
  • my $dereferenced = %$hash; <- here you want to do %dereferenced with the % sigil, or \%$hash thus passing a reference – Davs Jan 23 '14 at 08:02
  • Thanks! Sorry that I posted the duplicate question! Now I understood that the total Bucket size = 16. The number of Buckets that contain one or more elements = 7. Hence 7/16. This hash had more collisions itseems! – InnovWelt Jan 23 '14 at 10:56
  • @Borodin: I had thought in a different direction as follows. we can define a hash as %hash=(1,2,3,4). it actually means (1=>2, 3=>4). In the same way, dereferencing a hash reference should also return the same kind of array (if the LValue is not a Hash). in this case (1, 9, 2, 10, 3, 11 etc). So assigning this returned array to a scalar will be as same as calculating the array length ($length = @array). – InnovWelt Jan 23 '14 at 10:59

1 Answers1

1

Scalars cannot contain hashes or arrays, only references to them.

But even if they could, when you use a hash on the right side of a scalar assignment, it is in scalar context, and a hash in scalar context produces false if the hash is empty, or a string describing the bucket usage within the hash if not (e.g. "7/32").

Wolf
  • 9,679
  • 7
  • 62
  • 108
ysth
  • 96,171
  • 6
  • 121
  • 214
  • Eventhough, i have worked on perl for quite sometime, I didn't know how the hashing concept in perl works. Good to know the new term called 'Bucket'. thanks! – InnovWelt Jan 23 '14 at 10:53
  • @InnovWelt the term *Bucket* is not very helpful for becoming a better Perl programmer whereas knowing the meaning of ***scalar context*** is. – Wolf Mar 21 '17 at 11:48