Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Hash in Perl

Tags:

hash

perl

I want to know the following code why print "2/8".

#!/usr/bin/perl
#use strict;
#use warnings;
%a = ('a'=>'dfsd','b'=>'fdsfds');
print %a."\n";
like image 962
baozailove Avatar asked Mar 22 '13 06:03

baozailove


2 Answers

You are printing a hash in scalar context by concatenating it with a string '\n'

If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.

2/8 means that of the 8 buckets allocated, 2 have been touched. Considering that you've inserted only 2 values, it is doing well so far :)

The value is obviously of no use, except to evaluate how well the hash-function is doing. Use print %a; to print its contents.

like image 125
Anirudh Ramanathan Avatar answered Sep 23 '22 01:09

Anirudh Ramanathan


As mentioned by @Dark.. you are printing a hash in scalar context.

if you really want to print a hash, then use Data::Dumper

use Data::Dumper;
...
...
print Dumper(%a);

for eg:

use Data::Dumper; 
my %hash = ( key1 => 'value1', key2 => 'value2' ); 
print Dumper(%hash); # okay, but not great 
print "or\n"; 
print Dumper(\%hash); # much better

And the output:

$VAR1 = 'key2'; 
$VAR2 = 'value2'; 
$VAR3 = 'key1'; 
$VAR4 = 'value1'; 
or 
$VAR1 =    { 
             'key2' => 'value2', 
             'key1' => 'value1' 
           };
like image 24
Vijay Avatar answered Sep 23 '22 01:09

Vijay