I translated the Go example to Perl by making simple syntax transformations:
- Printing is done with
sayinstead offmt.Println. - Variables have a sigil that define their "type", for example,
$ainstead ofa. - Address of a variable is return with
\instead of&. - References/Pointers are dereferenced with
$instead of*. - Comments are made with
#instead of//. - Perl requires semicolons.
Here's the program:
use strict;
use warnings;
use feature 'say';
my $a = 1;
my $b = 2;
my $ap = \$a;
say("set ap to address of a (&a)");
say("ap address: ", $ap);
say("ap value: ", $$ap);
$$ap = 3;
say("change the value at address &a to 3");
say("ap address: ", $ap);
say("ap value: ", $$ap);
$a = 4;
say("change the value of a to 4");
say("ap address: ", $ap);
say("ap value: ", $$ap);
$ap = \$b;
say("set ap to the address of b (&b)");
say("ap address: ", $ap);
say("ap value: ", $$ap);
my $ap2 = $ap;
say("set ap2 to the address in ap");
say("ap address: ", $ap);
say("ap value: ", $$ap);
say("ap2 address: ", $ap2);
say("ap2 value: ", $$ap2);
$$ap = 5;
say("change the value at the address &b to 5");
# If this was a reference ap & ap2 would now
# have different values
say("ap address: ", $ap);
say("ap value: ", $$ap);
say("ap2 address: ", $ap2);
say("ap2 value: ", $$ap2);
$ap = \$a;
say("change ap to address of a (&a)");
# Since we've changed the address of ap, it now
# has a different value then ap2
say("ap address: ", $ap);
say("ap value: ", $$ap);
say("ap2 address: ", $ap2);
say("ap2 value: ", $$ap2);The result is identical to Go:
set ap to address of a (&a)
ap address: SCALAR(0x7fe55902d3d8)
ap value: 1
change the value at address &a to 3
ap address: SCALAR(0x7fe55902d3d8)
ap value: 3
change the value of a to 4
ap address: SCALAR(0x7fe55902d3d8)
ap value: 4
set ap to the address of b (&b)
ap address: SCALAR(0x7fe559030ed8)
ap value: 2
set ap2 to the address in ap
ap address: SCALAR(0x7fe559030ed8)
ap value: 2
ap2 address: SCALAR(0x7fe559030ed8)
ap2 value: 2
change the value at the address &b to 5
ap address: SCALAR(0x7fe559030ed8)
ap value: 5
ap2 address: SCALAR(0x7fe559030ed8)
ap2 value: 5
change ap to address of a (&a)
ap address: SCALAR(0x7fe55902d3d8)
ap value: 4
ap2 address: SCALAR(0x7fe559030ed8)
ap2 value: 5
If pointers and references are different nothing has yet been demonstrated; either that or Perl has pointers.