On Thursday 15 Jul 2010 13:54:01 Chanan Berler wrote:
> Hi All,
>
> following OO i have tried the following:
> but i found that there is a diffence between:
>
> #my $c1 = Number::Complex::new(2,5);
> my $c1 = new Number::Complex(2,5);
>
Yes, there is. And I should note that indirect-object notation("new
ClassName") is no longer advisable:
http://www.modernperlbooks.com/mt/2009/08/the-problems-with-indirect-object-
notation.html
Use "Number::Complex->new(...)" instead.
> Seems like I am getting a warning saying my number is not numeric ??!!
> (what tring to run the 'add' sub)
> Can any one explain it to me ?
> thanks
> Chanan
>
> This is what i tried:
> ================
> package Number::Complex;
> sub new
> {
> my ($real, $image) = @_;
> my $ref_c = { _real => $real, _image => $image };
> bless $ref_c, "Number::Complex";
> return $ref_c;
> }
If new is the constructor it should accept the $class first and do
«bless $ref_c, $class» . This constructor is wrong.
>
> sub toString
> {
> my $ref_c = shift; return "$ref_c->{_real} + $ref_c->{_image}i";
> }
Make sure you use accessors. See here for the motivation:
http://www.shlomifish.org/lecture/Perl/Newbies/lecture5/accessors/
>
> sub add
> {
> my ($ref_c1, $ref_c2) = @_;
> my $ref_c = Number::Complex::new($ref_c1->{_real} +
> $ref_c2->{_real}, $ref_c1->{_image} + $ref_c2->{_image});
> return $ref_c;
> }
Use Number::Complex->new() here.
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
First stop for Perl beginners - http://perl-begin.org/
God considered inflicting XSLT as the tenth plague of Egypt, but then
decided against it because he thought it would be too evil.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl