John Doe John Doe - 2 months ago 6x
Perl Question

References to equal strings

In Perl, if I create two references to an array element, the two pointers are equal.

my $ref1 = \$array[0];
my $ref2 = \$array[0];
print "$ref1\n$ref2";

The same applies to two references to a variable which stores a string, those pointers are equal.

If I create two variables in which I store equal strings, the references are not equal.

Why aren't they equal? The same data is stored in different places?

Does Perl refer to the variable instead of the memory location?

In Java, as you can see here, four equal strings refer to the same memory location.

Can somebody please explain that?


If you take several reference of one variable, all of them will point to the same memory location.

my $foo = 'foo';
my $ref1 = \$foo;
my $ref2 = \$foo;

say $ref1;
say $ref2;

The value behind $ref1 and $ref2 is the same, because they both point to the same variable.


If you assign the string (not the same variable containing a string) to two new variables and then take references for those, they will be different.

my $foo = 'foo';
my $bar = 'bar';
my $ref1 = \$foo;
my $ref2 = \$bar;

say $ref1;
say $ref2;

Here, $ref1 and $ref2 are not the same, because they are references to two different variables.


The fact that both variables hold an equal value doesn't matter.

my $ref1 = \'foo';
my $ref2 = \'foo';

say $ref1;
say $ref2;

The same goes for if you directly take references to values without putting them into another variable first.


Perl handles the memory internally, but it's not like it has a table with every possible string, and whenever you create a reference, it just uses that memory address.

In Java, strings are objects. Java knows about the objects that are available to it. When you define a string, it makes an object. That is not the case in Perl. Strings and numbers are just values, and they are put into memory when you use them.

What Perl does is keep track of its references. It will free up memory by removing unused values, but only if there are no more references to those values living somewhere else in the running program. That's called the ref count.

You can read about references in perlref. There also is a pretty good explanation of how all of this works in the book Object Oriented Perl by Damian Conway at Mannings.