Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: say variable in Class

by mr_ron (Chaplain)
on Jun 02, 2018 at 17:34 UTC ( #1215750=note: print w/replies, xml ) Need Help??


in reply to [Perl6] say variable in Class

Your code is almost valid Perl 6. In order to inspect attribute $!x you have to construct an object instance leading to the two suggestions below. See the Perl 6 Object Orientation document for more.

The first approach is a more usual starting point for development.

class A { has Str $.x ; method test { say 'Test'; say $!x ; } } A.new(x =>'hello').test;

The second approach is more advanced but may be closer to the OP intentions.

class A { has Str $.x ; submethod TWEAK { say 'Test'; say $!x ; } } A.new;
Ron

Replies are listed 'Best First'.
Re^2: say variable in Class
by Edelbaer (Initiate) on Jun 02, 2018 at 18:12 UTC

    Hello Ron,

    thank you for your reply. I think what you mean is that $.x would be accessible in the class as part of a method but not directly. Therefore your first method will work of course but defeats a bit the idea that the object on creation reports its status. The second approach works exactly as it should. And I guess now I need to learn why. So you were absolutely right about the intention :).

    Now I know what to learn, that is real progress!

    Thx a lot!

      but defeats a bit the idea that the object on creation reports its status
      If you want to do that, then you would probably need to create your own constructor with this added feature in it.

      Or, as shown by mr_ron, you might (re)define the TWEAK submethod, which is called by the new default constructor, so that redefining TWEAK effectively modifies the behavior of new.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1215750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2022-12-07 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?