I'm just wondering... since subroutines in Perl 6 are (like everything else) objects, whether state variables could be considered as public attributes, thus having an accessor, as in:

sub collect (Int *@nums) { state @data; @data.push(@nums); } # prepopulate it as late as possible: &collect.data.push(get_some_values); # ... # use collect(); my @collected = &collect.data;

Before anyone points it out: yes, I know that the example is trivial and there are OWTDI. Yet it's all about some syntactic sugar, and I don't know you, but I like it sweet. It also seems reliable enough to me but possibly for the clash with predefined methods, but there must an elegant and consistent way around...

Replies are listed 'Best First'.
Re: [Perl 6] State variables as public attributes?
by moritz (Cardinal) on Aug 26, 2007 at 20:26 UTC
    You can just use a class for that. You can have a member variable @data that you can initialize, access and modify, and provide methods that do the modifications.

    I don't see why a sub should get the functionality of a class.

    Or is there a use case where the OO metapher doesn't hold?

      I don't see why a sub should get the functionality of a class.

      Why should I use a class when I don't need the full power of a class and the overhead of writing one? can you provide some minimal code that would do the same as my pseudo code is supposed to?

      Or is there a use case where the OO metapher doesn't hold?

      Because as $Larry himeself wrote, the realm of Perl lies in pragmatism, and there are cases in which you don't mind metaphors, but want to do something in a practical and neat way. Had I to write a class for everything, I would go Java, I presume...

        class collector { has @.state; method collect(Int *@nums){ self.state.push: @nums; } }

        In fact for the example you have given a simple array is enough, but I assume you want to do a bit more in collect.

        The idea of OO is to bundle data with the methods that work on it, now you suggest to bundle a "state" with the method that works on it - for me it sounds like that's the same, or at least that it can use the same abstraction - classes.

        And I don't quite see the overhead in writing classes - snytactically that's class, a name and two curly braces.

        (Updated: fixed missing brace)