If in your first attempt (with unless @!items) you instead use: say "Items: " ~ $hamper.items.perl; you will get

Name: Christmas Basket Items: Array.new(:shape(3,), [Any, Any, Any])

The code has @.items[3] is rw; creates a positional attribute which contains a fixed-length array with 3 elements. Thus, the array is truthy and the unless is not triggered.

When you change to @!items := ('Mince Pie', 'White Wine', 'Stinky Cheese', 'Sardines', 'Dogfood'); you replace the fixed-kength array with a new List. Since @!items is rw that is allowed -- you aren't modifying the fixed length array, you are replacing it. Since the [3] describes the array, not the attribute, this is all fine -- to raku, though not perhaps to you :).

There may be a way to do this using has, but at some point it is reasonable to write your own accessor:

class Hamper { has $.name = 'Christmas Basket'; has Str @!items; method TWEAK(){ self.items = 'Mince Pie', 'White Wine', 'Stinky Cheese' unless + @!items; } method items() is rw { return-rw Proxy.new: FETCH => sub ($) { return @!items }, STORE => sub ($, @items) { die "Wrong length" unless @items.elems == 3; @!items = @items; }; } } my $hamper = Hamper.new; # $hamper.items = 'Mince Pie', 'White Wine', 'Stinky Cheese', 'Dogfood +'; say "Name: " ~ $hamper.name; say "Items: " ~ $hamper.items;

Good Day,
    Dean


In reply to Re: [Raku] Assigning defaults to attributes that are fixed length lists (and other confusions) by duelafn
in thread [Raku] Assigning defaults to attributes that are fixed length lists (and other confusions) by tomgracey

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.