|Do you know where your variables are?|
Autoboxing ... "Yes We Can" ( or how I learned to love TIMTOWTDI ;)by LanX (Chancellor)
|on Dec 13, 2013 at 18:30 UTC||Need Help??|
Perl is like one of these old text adventures, you keep collecting things from perldoc and suddenly you can open secret doors ...
There has always been much discussion (well flames) about a language idiom called "autoboxing"² missing in Perl.
I just stumbled over a way of emulating it in Perl by using "method" references.
Write an anonymous sub like a method, i.e. take $_ as $self.
Then call thing->$method_ref(args) and thing doesn't need to be blessed.
The documentationSee perlop:
The Arrow Operator
I used this technique in the past to either
See wikipedia, in short autoboxing allows to use a method call syntax on "things" which aren't blessed objects, like
The general idea is to combine the flexibility of method call syntax, avoiding the overhead to create a real object.
For instance a (contrived) example is JS which has the primitive type "string" and the class¹ "String". This allows to write
One way Perl could profit from such a syntax are nested data structures, where often manipulations result in ugly unDRYness and lots of nested punctuation.
A simple example: ¹
in JS you can not only avoid the sigil, you can also _chain_ method calls
There are more reasons to like autoboxing, there were attempts to overload -> to allow this in autobox but this is considered to be a too fragile hack.
Attempts to include this syntax as a language feature were regularly rejected / ignored / postponed.
IIRC does Perl6 intend to have it right away from the start.
And now ->$RFC
I was urged in the CB to write a meditation ASAP, so pardon me for typos, broken links and untested code³ which will need updates.
Being aware of fundamentalists hating this coding style I'm now counting the seconds till the outrage starts... =)
Others may want to add some other use cases ...
( addicted to the Perl Programming Language)
1) yes I know that push was extended "recently" to allow $arr_refs but 5.10 is still relevant
²) aka "boxing" aka "wrapper-classes" see also: wikipedia
³) and euphoria induced by coffee abuse