Ask and Learn
Ask and Learn

Reputation: 8959

Perl print %hash - need some help to understand this

Every simple Perl code but I don't understand it.

Here we go

#!/usr/bin/env perl
use warnings;
use strict;
my %hash;
$hash{"key"} = "value";
$hash{"key2"} = "value2";
$hash{"key3"} = "value3";
print %hash."\n";

And result is 3/8, remove one kep=>value pair, result is 2/8

If I removed the ."\n" then the result is expected key3value3key2value2keyvalue1

No reason to do this, noticed this accidentlly just try to understand what is happening.

Upvotes: 2

Views: 146

Answers (2)

James Green
James Green

Reputation: 1753

While Mark has covered what's going on here perfectly already, you can get the intended result without forcing the hash into scalar context by using "say %hash;" in versions of perl from 5.10 onwards or so.

You'll need to use feature 'say'; just as you would use warnings; (or to be running under perl -E, which switches on a number of "newer" features)

Upvotes: 3

Mark
Mark

Reputation: 2822

When you append the "\n" to the hash, you force the hash to be interpolated in scalar context, which causes it to print out its current capacity and size. When you remove it, the hash is interpolated in list context, and it prints out its current key/value pairs.

Upvotes: 7

Related Questions