develooper Front page | perl.perl6.users | Postings from June 2020

Re: proto and multi

Thread Previous | Thread Next
From:
Gianni Ceccarelli
Date:
June 29, 2020 18:38
Subject:
Re: proto and multi
Message ID:
20200629193131.6fbaf9ec@thenautilus.net
On 2020-06-29 Richard Hainsworth <rnhainsworth@gmail.com> wrote:
> a) I don't understand why the white space matters, but clearly it
> does. So the token is '{*}' and not braces around a Whatever-star.

Yep. Weird, but it's a special token.

> Not sure why the List:D is not being matched to Positional. Is the 
> List:D refering to the |c signature capture ??

Your method wants a `Positional @s`, which is an array/list/seq
containing only objects that do the `Positional` role. You're passing
it a list of strings. Either write `@s` (the @ implies you want a
positional thing) or `Positional $s` (a scalar containing a positional
object)

> c) Writing out all the code in each method is what I already have.
> But I'm looking for ways to factor out common code.

This works::

  class NewClass {
      has $.debug is rw = False;
      has $.value is rw = 'Initial value';

      proto method handle( |c ) {
            note "before value is $.value" if $.debug;
            {*}
            note "after value is $.value" if $.debug;
      }
      multi method handle(Str $s) {
          $.value = $s;
          say 'in string'
      }
      multi method handle(@s) {
          $.value = @s[0];
          say 'in positional'
      }
  }

  my NewClass $x .= new(:debug);

  $x.handle('hello world');
  $x.handle(<hello world>);

and prints::

  before value is Initial value
  in string
  after value is hello world
  before value is hello world
  in positional
  after value is hello

-- 
	Dakkar - <Mobilis in mobile>
	GPG public key fingerprint = A071 E618 DD2C 5901 9574
	                             6FE2 40EA 9883 7519 3F88
	                    key id = 0x75193F88

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About