On 20/07/17 11:51, Mark Carter wrote:
> I have a class definition:
> class Etran {
>         has $.dstamp is rw;
>         has $.folio is rw;
>         has $.ticker is rw;
>         has $.qty is rw;
>         has $.amount is rw;
>         has $.desc is rw;
>         method new($line) {
>                 my ($cmd, $dstamp, $folio, $ticker, $qty, $amount, $way, 
> $desc) = shlex-fields $line;
>                 $!dstamp = $dstamp;
>                 $!folio = $folio;
>                 $!ticker = $ticker;
>                 $!qty = $way == "B" ?? $qty !! - $qty;
>                 $!amount = $amount;
>                 $!desc = $desc;
>         }
> }**
> which I instantiate with
>       my $e = Etran.new($line);
> However, it gives an error message:
>       Cannot look up attributes in a Etran type object
> at the line 
>       $!dstamp = $dstamp;
> Why that, and how do I fix it?
> Also, I don't really understand the difference between using the twigils "." 
> and using "!",
> and have yet to see an explanation that I understand.
The method new is invoked on the type Etran itself, not an instance of
it. As such, no storage space exists to put the data into.

What you really want is to create a new Etran object using "self.bless"
and passing all of your variables as named arguments.

Another thing is that you're trying to compare strings with == ($way vs
"B"), but == is numerical comparison and as such will try to numify "B"
and whatever is in $way. You'll want the "eq" operator instead.

There are multiple differences between $. and $! - "$.foo" is just
short-hand for "self.foo.item", and since you'd usually use the "$.foo"
syntax with attributes only, you'll be using the accessor method that
gets created for you.

$! on the other hand directly accesses the underlying storage for the
attribute. These are private to the class that defines them.

Hope that helps a bit?
  - Timo

Reply via email to