p5h / p5summit-2019

Perl 5 Summit
0 stars 0 forks source link

autoboxing #11

Open leonerd opened 4 years ago

leonerd commented 4 years ago

With the addition of IO::Handle in some automatic magic around 5.12 (I forget the exact history), you can now just do things like

my $line = $fh->readline;

and even if $fh is just a regular filehandle calling an IO method on it like that works just fine. But if it happens to be a fancy object with a real method, then that works too. It's great, I use this all the time whenever my modules expect an IO-like value to be passed in. Users can give me a real IO handle in real code, or a totally virtual thing maybe in a unit test or whatever, and all works out fine.

Why can't we do this for arrays and hashes too?

Specifically,

$ perl -E 'my $arr = [];  $arr->push(1,2,3)'
Can't call method "push" on unblessed reference at -e line 1.

We can sortof fake this up with

$ perl -E \
  'sub ARRAY::push { push $_[0]->@*, @_[1..$#_] }
   my $arr = bless [], "ARRAY";
   $arr->push(1,2,3);
   say for @$arr'
1
2
3

but it'd be great if that happened automatically.

leonerd commented 4 years ago

I think the thrust of my question is, basically, why don't all unblessed references already act as if they were actually objects in classes called ARRAY, HASH, etc..., whose packages were already prepopulated with methods that behave "as expected"?