in reply to How to swap scalar values without copies

My curiosity has finally got the best of me, and I can no longer resist asking (though I really tried to let it go) why references are out of the question.

As an OO programmer you're certanly comfortable with references already, so there must be a good reason why they can't be used in this case.

I'm unable to restrain myself from posing the question. I hope I'm about to learn something new. ;)


Dave

  • Comment on Re: How to swap scalar values without copies

Replies are listed 'Best First'.
Re: Re: How to swap scalar values without copies
by Anonymous Monk on Feb 20, 2004 at 18:25 UTC
    Well, I'm currently confortable with C++ references. Although the name is the same, the syntax is different. In C++ I can write:
    int &pluto = pippo;
    and, from now on (up to the end of its scope), pluto is just a synonim for pippo. I'am not asserting I can do this for an object member.

    In C++, if I have a class member named data, in a method of that class I can simply refer to it as data, which is the same as this->data. In Perl, the same member must be referred to as $this->{data}, in addition to explicitely setting the object pointer every time: my $this = shift;, for instance.

    But, if I store a reference, I am obliged to refer to the corresponding scalar as ${$this->{data}}, and this clutters the code way too much for me ($$data would be acceptable) . Please, tell me that I am wrong and I can save all this typing.

    Moreover, just saving a reference to an argument as a class member is not completely satisfactory. The top of my dreams would be that the passed buffer becomes a private member, i.e. it is not possible to modify it from outside the constructor by referring to the actual argument:

    read(IN, $buffer, 1000000); push @mysegments, new MyPackage::MySegment($buffer); print "+$buffer+"; # gives ++
    but the buffer is still living as a private member in my object.