Re: How to get indirect access to a class attribute?
On Mar 25, 2015, at 7:44 AM, Tom Browder tom.brow...@gmail.com wrote: —snip-- 1. How can I indirectly refer to the attributes in a method? The above doesn't work (with or without the '()’). —snip— use v6; our %attrs = ( age = 1, # wgt = 2, # Need to handle No such method before uncommenting. ); class foo { # has $.age = rw; has $.age; method all_attrs { my @ordered_attrs = %attrs.sort({ + .value }).map({ .key }); for @ordered_attrs - $k { my $aval = self.$k(); # supposed to work for a method name say attr { $k } has value '{ $aval }'; } } } my $f = foo.new( age = 30 ); # say $f.perl; $f.all_attrs(); My modified version of your code (above) works for me. Output is: attr age has value '30' Note that your line has $.age = rw was invalid syntax, and your a method was *outside* your original foo class. — Hope this helps, Bruce Gray (Util of PerlMonks)
Re: How to get indirect access to a class attribute?
On Wed, Mar 25, 2015 at 8:47 AM, Tom Browder tom.brow...@gmail.com wrote: On Wed, Mar 25, 2015 at 8:29 AM, Moritz Lenz mor...@faui2k3.org wrote: the indirect method call syntax is the right approach, you just got too many other details wrong to make it work. This syntax works in a method as you said: self.$elem() Again I was getting errors that masked the correctness of that syntax--incomplete debugging! Thanks all. Cheers! -Tom Fair enough--my fingers fumbled a few important things. I'll correct and recheck; Thanks, Moritz (and Bruce). Cheers! -Tom
How to get indirect access to a class attribute?
Given a class like: our %attrs = (age=1,wgt=2); class foo { has $.age = rw;} method a { for %attrs.kv - $k, $v { my $aval = self.$k(); # supposed to work for a method name say attr { $k } has value '{ $aval }'; } } Question: 1. How can I indirectly refer to the attributes in a method? The above doesn't work (with or without the '()'). 2. Do I have to write a custom accessor to do so? Thanks. Best regards, -Tom
Re: How to get indirect access to a class attribute?
Hi, On 25.03.2015 13:44, Tom Browder wrote: Given a class like: our %attrs = (age=1,wgt=2); class foo { has $.age = rw;} should be 'has $.age is rw'. The is indicates a trait (not an assignment). method a { for %attrs.kv - $k, $v { my $aval = self.$k(); # supposed to work for a method name Etiher method a needs to be inside class foo, or it needs to be a subroutine, and refer to foo instead of self here. A method outside a class doesn't ususally make sense, which is why you get this message: Other potential difficulties: Useless declaration of a has-scoped method in mainline (did you mean 'my method a'?) say attr { $k } has value '{ $aval }'; } } Question: 1. How can I indirectly refer to the attributes in a method? The above doesn't work (with or without the '()'). the indirect method call syntax is the right approach, you just got too many other details wrong to make it work. Cheers, Moritz