Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Support overloaded stringification of P5 objects
In Perl 5:
package Foo; use overload '""' => sub { "foo!" };
In Perl 6:
say $foo.Str(); # gives "foo!"
  • Loading branch information
niner committed Jun 14, 2015
1 parent c1b6df5 commit 035eb53
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/Inline/Perl5.pm6
Expand Up @@ -670,6 +670,11 @@ class Perl5Object {

method sink() { self }

method Str() {
my $stringify = $!perl5.call('overload::Method', self, '""');
return $stringify ?? $stringify(self) !! callsame;
}

method DESTROY {
$!perl5.sv_refcnt_dec($!ptr) if $!ptr;
$!ptr = OpaquePointer;
Expand Down
39 changes: 39 additions & 0 deletions t/overload.t
@@ -0,0 +1,39 @@
#!/usr/bin/env perl6

use v6;
use Inline::Perl5;
use Test;

my $p5 = Inline::Perl5.new;

$p5.run: q:heredoc/PERL5/;
package Foo;
use overload '""' => sub {
my ($self) = @_;
return $$self;
};
sub new {
my ($class, $str) = @_;
return bless \$str, $class;
}
my $foo = Foo->new("foo");
package Bar;
sub new {
my ($class, $str) = @_;
return bless \$str, $class;
}
PERL5

my $foo = $p5.invoke('Foo', 'new', 'a string!');
is("$foo", 'a string!');
unlike("$foo", /Perl5Object\<\d+\>/);

my $bar = $p5.invoke('Bar', 'new', 'a string!');
isnt("$bar", 'a string!');
like("$bar", /Perl5Object\<\d+\>/);

done;

# vim: ft=perl6

0 comments on commit 035eb53

Please sign in to comment.