Perl is quantum

2015-04-21

Type coercion as usual

Like many languages perl has type coercion; if you use a string in an integer context everything will work fine as long as that string is sufficiently integer-ish

print "3" + 1; # outputs 4

This behaves initially as expected when we introduce indirection via variables

use Data::Dumper;
my $a = "3";
say Dumper $a;

will output:

$VAR1 = '3';

which is Data::Dumper::Dumper helpfully telling us $a contains a string with value '3'.

When things go astray

However perl gets a little strange when we try read that value in an integer context before printing it:

use Data::Dumper;
my $a = "3";
my $b = $a + 1;
say Dumper $a;

perl will output:

$VAR1 = 3;

which is now telling us that the contents of $a are now an integer with value 3.

What is interesting here is that there was no explicit assignment to $a, the "mutation" of $a was "for free".

What is happening

The mere act of observing a variable in a specific context changes not only the interpretation of the value but also the contents of the variable.

That is in perl every variable read where you coerce the fetched value is also a write of that coerced values back to the variable.

A concise example

The complete example in action:

#!/usr/bin/env perl
use strict;
use warnings;
use v5.10;
use Data::Dumper;

my $a = "1";
say Dumper $a;

my $b = $a + 1;
say Dumper $a;

which outputs:

$VAR1 = '1';
$VAR1 = 1;

Summary

Perl is well equipped for the quantum revolution with it's excellent support for what I will now start calling "Schrodinger variables".

The most likely reason for this is an optimisation to prevent the need for perl to re-coerce on subsequent reads in the same context.