On Dec 6, christopher j bottaro said:

>i'm a c/c++ programmer trying to learn perl.  there are just some things that
>are much more easily done in a language like perl than in c/c++ i've found
>out...=)  anyways, i'm reading a short tutorial about references.  am i wrong
>in thinking they are like pointers in c/c++?

They are similar in purpose, different in implementation.  As a C
programm, you hopefully know that pointers can be manipulated:

  int num[5] = { 2, 4, 8, 16, 32 };
  int *n = num;

  printf("%d + %d = %d\n", *n, *(n+1), *n + *(n+1));  # 2 + 4 = 6

You can add and subtract from pointers and C will "do the right thing".
Specifically, (n + 1) becomes (n + 1 * sizeof(*n)).

In fact, we don't even NEED n here, because arrays are implicitly
pointers.  nums[0] is really *(nums + 0), and nums[1] is really *(nums +
1), which is really *(nums + 1 * sizeof(*nums)).

So, now that I've spilled the beans on pointers, how are Perl's references
not the same as pointers?  Well, Perl doesn't appreciate you mucking
around with the internals of its data storage.  You can't go:

  @nums = (1 .. 5);
  $nref = \@nums;
  print $$nref, $($nref + 1);

It doesn't work that way in Perl at ALL.  First of all, $$nref treats
$nref as a SCALAR reference, not an ARRAY reference.  Second, $(...) isn't
valid Perl syntax.  ${$nref + 1} is valid, but doesn't do anything like
you'd expect.

You can't do the equivalent of "pointer arithmetic" in Perl.  You merely
use the data the reference refers to:

  print $nref->[0], $nref->[1];  # like $nums[0], $nums[1]

Someone COULD write a Pointer class in Perl:

  use Pointer;
  my $p = Pointer->new([1 .. 5]);
  print $$p, ${$p + 1};

but I'd really question the usefulness of such a thing.  I'd write it, but
I'm afraid it would fall into the wrong hands and cause the sudden heat
death of the Universe.  Or would make a C or C++ programmer treat Perl
like C (no offense).

And Pointer.pm would need to do a whole lot overloading operators.  And
that's too much work for me right now. ;)

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to