Skip to content

Instantly share code, notes, and snippets.

@nnutter
Created July 2, 2014 01:45
Show Gist options
  • Select an option

  • Save nnutter/65b454bc7df9f2b6bffd to your computer and use it in GitHub Desktop.

Select an option

Save nnutter/65b454bc7df9f2b6bffd to your computer and use it in GitHub Desktop.
Pointers vs. References

I translated the Go example to Perl by making simple syntax transformations:

  • Printing is done with say instead of fmt.Println.
  • Variables have a sigil that define their "type", for example, $a instead of a.
  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment