lonewolf28 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Fellow Monks, I was playing around with OO perl and i wanted to test if i could replicate __str__ operator method in python with Perl OO. So i created a trivial code to test it out. The code doesn't throw any error, however, i don't get any output either.

#!/usr/bin/perl use v5.22; use overload '""' => 'stringify'; use Data::Dumper; package oo_test{ sub new{ my $class = shift; my $self = {}; bless $self, $class; return $self; } sub getter{ my $self = shift; while( my $line = <DATA> ){ chomp $line; $self->{$.} = $line; } return $self; } sub stringify{ my $self = shift; return join(" ", values %$self ); } }; package main; my $test = oo_test->new(); $test->getter(); print $test->stringify; __DATA__ Hi How Are You

I'm sure that i'm making some mistakes. I'd like to admit that my OO perl is bit shaky.

Replies are listed 'Best First'.
Re^2: Operator overloading question
by BrowserUk (Patriarch) on Oct 26, 2015 at 03:41 UTC

    The pseudo handle DATA looks for a __DATA__ section in the current package; but the only __DATA__ section you have is in main; hence the while loop does nothing, the object contains no data, and stringify() correctly returns nothing.

    Replace while( my $line = <DATA> ){ with while( my $line = <main::DATA> ){ and your code works.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: Operator overloading question
by shmem (Chancellor) on Oct 26, 2015 at 06:02 UTC

    Apart from the mistake BrowserUk pointed out, there are two more:

    • you use overload in package main, so oo_test doesn't have overload included - instead overload binds '""' to main::stringify, which doesn't exist
    • to properly invoke the overloaded function, you should print "$test", not invoke stringify as method upon $test

    #!/usr/bin/perl use v5.22; use Data::Dumper; package oo_test{ use overload '""' => 'stringify'; sub new{ my $class = shift; my $self = {}; bless $self, $class; return $self; } sub getter{ my $self = shift; while( my $line = <main::DATA> ){ print $line; chomp $line; $self->{$.} = $line; } return $self; } sub stringify{ my $self = shift; return join(" ", values %$self ); } }; package main; my $test = oo_test->new(); $test->getter(); print "$test\n"; __DATA__ Hi How Are You
    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

      Thank you shmen. You showed me a better way to do it.