user5306780
user5306780

Reputation:

How to assign hash with predefined hash value in Perl?

Suppose i have a hash variable in a Perl script. I print its value in following way:

print \%MyHash;

and obtain following output: HASH(0x33fa1fc)

I receive the same output consistently during many executions. For my prototyping purposes i would like to refer to this number in another script.

How can I do it? Should I try something similar to this?

my %MyHash;
$MyHash = Ox33fa1fc;

Upvotes: 2

Views: 132

Answers (2)

ikegami
ikegami

Reputation: 386706

It's the memory address of the hash.

For example,

use Devel::Peek  qw( Dump );
use Scalar::Util qw( refaddr );
my %h;
CORE::say(\%h);
CORE::say(sprintf("%x", refaddr(\%h)));
Dump(\%h, 0);

could output

HASH(0x1454af8)                   <-- The stringification of the reference.
1454af8                           <-- The address of the referenced variable.
SV = IV(0x1435eb0) at 0x1435ec0   <-- The scalar passed to Dump...
  REFCNT = 1
  FLAGS = (TEMP,ROK)              <-- ...is a reference...
  RV = 0x1454af8                  <-- ...and this is the address of the referenced variable.

Since each process has its own memory space, this value is useless outside of the process that generated it. You can't build a reference that references this hash from another process (and it wouldn't be safe to have to processes accessing the same hash if you could).


I receive the same output consistently during many executions.

By the way, there's no guarantee of that. In fact, it's not the case on my system.

$ for q in 1 2 3; do perl -e'my %h; CORE::say(\%h);'; done
HASH(0x100c878)
HASH(0x1a08758)
HASH(0x45a31e8)

Upvotes: 1

Dave Mitchell
Dave Mitchell

Reputation: 2403

The hex number is just the address where the hash variable happens to reside in memory. It can and will change with different releases of perl, and different releases of the operating system, or with minor changes in the execution of the code. It cannot be relied upon being the same across scripts, and perl provides no facility to convert an address back into a variable.

Upvotes: 3

Related Questions