Returns the glob with the given C<name> and a defined subroutine or
C<NULL>. The glob lives in the given C<stash>, or in the stashes
-accessible via @ISA and @UNIVERSAL.
+accessible via @ISA and @UNIVERSAL.
The argument C<level> should be either 0 or -1. If C<level==0>, as a
side-effect creates a glob with the given C<name> in the given C<stash>
which in the case of success contains an alias for the subroutine, and sets
-up caching info for this glob. Similarly for all the searched stashes.
+up caching info for this glob. Similarly for all the searched stashes.
This function grants C<"SUPER"> token as a postfix of the stash name. The
GV returned from C<gv_fetchmeth> may be a method cache entry, which is not
visible to Perl code. So when calling C<call_sv>, you should not use
the GV directly; instead, you should use the method's CV, which can be
-obtained from the GV with the C<GvCV> macro.
+obtained from the GV with the C<GvCV> macro.
=cut
*/
Returns the glob which contains the subroutine to call to invoke the method
on the C<stash>. In fact in the presence of autoloading this may be the
glob for "AUTOLOAD". In this case the corresponding variable $AUTOLOAD is
-already setup.
+already setup.
The third parameter of C<gv_fetchmethod_autoload> determines whether
AUTOLOAD lookup is performed if the given method is not present: non-zero
-means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
+means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
-with a non-zero C<autoload> parameter.
+with a non-zero C<autoload> parameter.
These functions grant C<"SUPER"> token as a prefix of the method name. Note
that if you want to keep the returned glob for a long time, you need to
check for it being "AUTOLOAD", since at the later time the call may load a
different subroutine due to $AUTOLOAD changing its value. Use the glob
-created via a side effect to do this.
+created via a side effect to do this.
These functions have the same side-effects and as C<gv_fetchmeth> with
C<level==0>. C<name> should be writable if contains C<':'> or C<'
''>. The warning against passing the GV returned by C<gv_fetchmeth> to
-C<call_sv> apply equally to these functions.
+C<call_sv> apply equally to these functions.
=cut
*/
register const char *nend;
const char *nsplit = 0;
GV* gv;
-
+
for (nend = name; *nend; nend++) {
if (*nend == '\'')
nsplit = nend;
/*
* Inheriting AUTOLOAD for non-methods works ... for now.
*/
- if (ckWARN(WARN_DEPRECATED) && !method &&
+ if (ckWARN(WARN_DEPRECATED) && !method &&
(GvCVGEN(gv) || GvSTASH(gv) != stash))
Perl_warner(aTHX_ WARN_DEPRECATED,
"Use of inherited AUTOLOAD for non-method %s::%.*s() is deprecated",
void
Perl_gp_free(pTHX_ GV *gv)
{
- dTHR;
+ dTHR;
GP* gp;
if (!gv || !(gp = GvGP(gv)))
AV *GvAVn(gv)
register GV *gv;
{
- if (GvGP(gv)->gp_av)
+ if (GvGP(gv)->gp_av)
return GvGP(gv)->gp_av;
else
return GvGP(gv_AVadd(gv))->gp_av;
for (i = 1; i < NofAMmeth; i++) {
cv = 0;
cp = (char *)PL_AMG_names[i];
-
+
svp = (SV**)hv_fetch(hv, cp, strlen(cp), FALSE);
if (svp && ((sv = *svp) != &PL_sv_undef)) {
switch (SvTYPE(sv)) {
/* GvSV contains the name of the method. */
GV *ngv;
- DEBUG_o( Perl_deb(aTHX_ "Resolving method `%.256s' for overloaded `%s' in package `%.256s'\n",
+ DEBUG_o( Perl_deb(aTHX_ "Resolving method `%.256s' for overloaded `%s' in package `%.256s'\n",
SvPV(GvSV(gv), n_a), cp, HvNAME(stash)) );
- if (!SvPOK(GvSV(gv))
+ if (!SvPOK(GvSV(gv))
|| !(ngv = gv_fetchmethod_autoload(stash, SvPVX(GvSV(gv)),
FALSE)))
{
/* Can be an import stub (created by `can'). */
if (GvCVGEN(gv)) {
- Perl_croak(aTHX_ "Stub found while resolving method `%.256s' overloading `%s' in package `%.256s'",
+ Perl_croak(aTHX_ "Stub found while resolving method `%.256s' overloading `%s' in package `%.256s'",
(SvPOK(GvSV(gv)) ? SvPVX(GvSV(gv)) : "???" ),
cp, HvNAME(stash));
} else
- Perl_croak(aTHX_ "Can't resolve method `%.256s' overloading `%s' in package `%.256s'",
+ Perl_croak(aTHX_ "Can't resolve method `%.256s' overloading `%s' in package `%.256s'",
(SvPOK(GvSV(gv)) ? SvPVX(GvSV(gv)) : "???" ),
cp, HvNAME(stash));
}
GvNAME(CvGV(cv))) );
filled = 1;
}
-#endif
+#endif
amt.table[i]=(CV*)SvREFCNT_inc(cv);
}
if (filled) {
Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
{
dTHR;
- MAGIC *mg;
- CV *cv;
+ MAGIC *mg;
+ CV *cv;
CV **cvp=NULL, **ocvp=NULL;
AMT *amtp, *oamtp;
int fl=0, off, off1, lr=0, assign=AMGf_assign & flags, notfound=0;
HV* stash;
if (!(AMGf_noleft & flags) && SvAMAGIC(left)
&& (mg = mg_find((SV*)(stash=SvSTASH(SvRV(left))),'c'))
- && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
+ && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
: (CV **) NULL))
- && ((cv = cvp[off=method+assignshift])
+ && ((cv = cvp[off=method+assignshift])
|| (assign && amtp->fallback > AMGfallNEVER && /* fallback to
* usual method */
(fl = 1, cv = cvp[off=method])))) {
(void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
break;
case not_amg:
- (void)((cv = cvp[off=bool__amg])
+ (void)((cv = cvp[off=bool__amg])
|| (cv = cvp[off=numer_amg])
|| (cv = cvp[off=string_amg]));
postpr = 1;
}
break;
case abs_amg:
- if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
+ if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
&& ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
SV* nullsv=sv_2mortal(newSViv(0));
if (off1==lt_amg) {
}
break;
case iter_amg: /* XXXX Eventually should do to_gv. */
+ /* FAIL safe */
+ return NULL; /* Delegate operation to standard mechanisms. */
+ break;
case to_sv_amg:
case to_av_amg:
case to_hv_amg:
case to_gv_amg:
case to_cv_amg:
/* FAIL safe */
- return NULL; /* Delegate operation to standard mechanisms. */
+ return left; /* Delegate operation to standard mechanisms. */
break;
default:
goto not_found;
if (!cv) goto not_found;
} else if (!(AMGf_noright & flags) && SvAMAGIC(right)
&& (mg = mg_find((SV*)(stash=SvSTASH(SvRV(right))),'c'))
- && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
+ && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
? (amtp = (AMT*)mg->mg_ptr)->table
: (CV **) NULL))
&& (cv = cvp[off=method])) { /* Method for right
* argument found */
lr=1;
- } else if (((ocvp && oamtp->fallback > AMGfallNEVER
- && (cvp=ocvp) && (lr = -1))
+ } else if (((ocvp && oamtp->fallback > AMGfallNEVER
+ && (cvp=ocvp) && (lr = -1))
|| (cvp && amtp->fallback > AMGfallNEVER && (lr=1)))
&& !(flags & AMGf_unary)) {
/* We look for substitution for
}
} else {
not_found: /* No method found, either report or croak */
+ switch (method) {
+ case to_sv_amg:
+ case to_av_amg:
+ case to_hv_amg:
+ case to_gv_amg:
+ case to_cv_amg:
+ /* FAIL safe */
+ return left; /* Delegate operation to standard mechanisms. */
+ break;
+ }
if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
notfound = 1; lr = -1;
} else if (cvp && (cv=cvp[nomethod_amg])) {
} else {
SV *msg;
if (off==-1) off=method;
- msg = sv_2mortal(Perl_newSVpvf(aTHX_
+ msg = sv_2mortal(Perl_newSVpvf(aTHX_
"Operation `%s': no method found,%sargument %s%s%s%s",
PL_AMG_names[method + assignshift],
(flags & AMGf_unary ? " " : "\n\tleft "),
- SvAMAGIC(left)?
+ SvAMAGIC(left)?
"in overloaded package ":
"has no overloaded magic",
- SvAMAGIC(left)?
+ SvAMAGIC(left)?
HvNAME(SvSTASH(SvRV(left))):
"",
- SvAMAGIC(right)?
+ SvAMAGIC(right)?
",\n\tright argument in overloaded package ":
- (flags & AMGf_unary
+ (flags & AMGf_unary
? ""
: ",\n\tright argument has no overloaded magic"),
- SvAMAGIC(right)?
+ SvAMAGIC(right)?
HvNAME(SvSTASH(SvRV(right))):
""));
if (amtp && amtp->fallback >= AMGfallYES) {
}
}
if (!notfound) {
- DEBUG_o( Perl_deb(aTHX_
+ DEBUG_o( Perl_deb(aTHX_
"Overloaded operator `%s'%s%s%s:\n\tmethod%s found%s in package %s%s\n",
PL_AMG_names[off],
method+assignshift==off? "" :
flags & AMGf_unary? "" :
lr==1 ? " for right argument": " for left argument",
flags & AMGf_unary? " for argument" : "",
- HvNAME(stash),
+ HvNAME(stash),
fl? ",\n\tassignment variant used": "") );
}
/* Since we use shallow copy during assignment, we need
* b) Increment or decrement, called directly.
* assignshift==0, assign==0, method + 0 == off
* c) Increment or decrement, translated to assignment add/subtr.
- * assignshift==0, assign==T,
+ * assignshift==0, assign==T,
* force_cpy == T
* d) Increment or decrement, translated to nomethod.
- * assignshift==0, assign==0,
+ * assignshift==0, assign==0,
* force_cpy == T
* e) Assignment form translated to nomethod.
* assignshift==1, assign==T, method + 1 != off
}
%constants = (
- 'integer' => 0x1000,
+ 'integer' => 0x1000,
'float' => 0x2000,
'binary' => 0x4000,
'q' => 0x8000,
__END__
-=head1 NAME
+=head1 NAME
overload - Package for overloading perl operations
package SomeThing;
- use overload
+ use overload
'+' => \&myadd,
'-' => \&mysub;
# etc
package Number;
use overload
- "+" => \&add,
+ "+" => \&add,
"*=" => "muas";
declares function Number::add() for addition, and method muas() in
the "class" C<Number> (or one of its base classes)
-for the assignment form C<*=> of multiplication.
+for the assignment form C<*=> of multiplication.
Arguments of this directive come in (key, value) pairs. Legal values
are values legal inside a C<&{ ... }> call, so the name of a
=back
B<Warning.> Due to the presense of assignment versions of operations,
-routines which may be called in assignment context may create
-self-referential structures. Currently Perl will not free self-referential
+routines which may be called in assignment context may create
+self-referential structures. Currently Perl will not free self-referential
structures until cycles are C<explicitly> broken. You may get problems
when traversing your structures too.
-Say,
+Say,
use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
is asking for trouble, since for code C<$obj += $foo> the subroutine
-is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
+is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
\$foo]>. If using such a subroutine is an important optimization, one
can overload C<+=> explicitly by a non-"optimized" version, or switch
-to non-optimized version if C<not defined $_[2]> (see
+to non-optimized version if C<not defined $_[2]> (see
L<Calling Conventions for Binary Operations>).
Even if no I<explicit> assignment-variants of operators are present in
should be of correct type. These functions should return a reference
of correct type, or another object with overloaded dereferencing.
+As a special case if the overload returns the object itself then it
+will be used directly (provided it is the correct type).
+
+The dereference operators must be specified explicitly they will not be passed to
+"nomethod".
+
=item * I<Special>
"nomethod", "fallback", "=",
if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
C<use overload> directive.
+The C<"nomethod"> mechanism is I<not> used for the dereference operators
+( ${} @{} %{} &{} *{} ).
+
+
If some operation cannot be resolved, and there is no function
assigned to C<"nomethod">, then an exception will be raised via die()--
unless C<"fallback"> was specified as a key in C<use overload> directive.
-=head2 Fallback
+
+=head2 Fallback
The key C<"fallback"> governs what to do if a method for a particular
operation is not found. Three different cases are possible depending on
=item * defined, but FALSE
No autogeneration is tried. Perl tries to call
-C<"nomethod"> value, and if this is missing, raises an exception.
+C<"nomethod"> value, and if this is missing, raises an exception.
=back
to a reference that shares its object with some other reference, such
as
- $a=$b;
+ $a=$b;
++$a;
To make this change $a and not change $b, a copy of C<$$a> is made,
C<nomethod>). Note that if this operation is expressed via C<'+'>
a nonmutator, i.e., as in
- $a=$b;
+ $a=$b;
$a=$a+1;
then C<$a> does not reference a new copy of C<$$a>, since $$a does not
=item B<Example>
-The actually executed code for
+The actually executed code for
- $a=$b;
+ $a=$b;
Something else which does not modify $a or $b....
++$a;
may be
- $a=$b;
+ $a=$b;
Something else which does not modify $a or $b....
$a = $a->clone(undef,"");
$a->incr(undef,"");
C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
is not defined.
-=item I<Conversion operations>
+=item I<Conversion operations>
String, numeric, and boolean conversion are calculated in terms of one
another if not all of them are defined.
can be expressed in terms of string conversion.
-=item I<Comparison operations>
+=item I<Comparison operations>
can be expressed in terms of its "spaceship" counterpart: either
C<E<lt>=E<gt>> or C<cmp>:
The corresponding values are references to functions which take three arguments:
the first one is the I<initial> string form of the constant, the second one
-is how Perl interprets this constant, the third one is how the constant is used.
+is how Perl interprets this constant, the third one is how the constant is used.
Note that the initial string form does not
-contain string delimiters, and has backslashes in backslash-delimiter
+contain string delimiters, and has backslashes in backslash-delimiter
combinations stripped (thus the value of delimiter is not relevant for
-processing of this string). The return value of this function is how this
+processing of this string). The return value of this function is how this
constant is going to be interpreted by Perl. The third argument is undefined
unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
context (comes from strings, regular expressions, and single-quote HERE
-documents), it is C<tr> for arguments of C<tr>/C<y> operators,
+documents), it is C<tr> for arguments of C<tr>/C<y> operators,
it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
it is expected that overloaded constant strings are equipped with reasonable
-overloaded catenation operator, otherwise absurd results will result.
+overloaded catenation operator, otherwise absurd results will result.
Similarly, negative numbers are considered as negations of positive constants.
Note that it is probably meaningless to call the functions overload::constant()
overload::constant integer => sub {Math::BigInt->new(shift)};
}
-B<BUGS> Currently overloaded-ness of constants does not propagate
+B<BUGS> Currently overloaded-ness of constants does not propagate
into C<eval '...'>.
=head1 IMPLEMENTATION
package. This magic is three-words-long for packages without
overloading, and carries the cache table if the package is overloaded.
-Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
+Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
carried out before any operation that can imply an assignment to the
object $a (or $b) refers to, like C<$a++>. You can override this
behavior by defining your own copy constructor (see L<"Copy Constructor">).
=head1 Metaphor clash
One may wonder why the semantic of overloaded C<=> is so counter intuitive.
-If it I<looks> counter intuitive to you, you are subject to a metaphor
-clash.
+If it I<looks> counter intuitive to you, you are subject to a metaphor
+clash.
Here is a Perl object metaphor:
The difference is not relevant in the absence of mutators. After
a Perl-way assignment an operation which mutates the data referenced by $a
-would change the data referenced by $b too. Effectively, after
+would change the data referenced by $b too. Effectively, after
C<$a = $b> values of $a and $b become I<indistinguishable>.
-On the other hand, anyone who has used algebraic notation knows the
+On the other hand, anyone who has used algebraic notation knows the
expressive power of the arithmetic metaphor. Overloading works hard
to enable this metaphor while preserving the Perlian way as far as
possible. Since it is not not possible to freely mix two contradicting
way it is done is described in L<Copy Constructor>.
If some mutator methods are directly applied to the overloaded values,
-one may need to I<explicitly unlink> other values which references the
+one may need to I<explicitly unlink> other values which references the
same value:
$a = new Data 23;
preserve "objectness" of $a. But Perl I<has> a way to make assignments
to an object do whatever you want. It is just not the overload, but
tie()ing interface (see L<perlfunc/tie>). Adding a FETCH() method
-which returns the object itself, and STORE() method which changes the
+which returns the object itself, and STORE() method which changes the
value of the object, one can reproduce the arithmetic metaphor in its
completeness, at least for variables which were tie()d from the start.
package two_refs;
use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
- sub new {
- my $p = shift;
+ sub new {
+ my $p = shift;
bless \ [@_], $p;
}
sub gethash {
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
- sub STORE {
+ sub STORE {
my $self = ${shift()};
my $key = $fields{shift()};
defined $key or die "Out of band access";
$$self->[$key] = shift;
}
- sub FETCH {
+ sub FETCH {
my $self = ${shift()};
my $key = $fields{shift()};
defined $key or die "Out of band access";
sub access_hash {
my ($self, $key) = (shift, shift);
my $class = ref $self;
- bless $self, 'overload::dummy'; # Disable overloading of %{}
+ bless $self, 'overload::dummy'; # Disable overloading of %{}
my $out = $self->{$key};
bless $self, $class; # Restore overloading
$out;
package two_refs1;
use overload '%{}' => sub { ${shift()}->[1] },
'@{}' => sub { ${shift()}->[0] };
- sub new {
- my $p = shift;
+ sub new {
+ my $p = shift;
my $a = [@_];
my %h;
tie %h, $p, $a;
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
- sub STORE {
+ sub STORE {
my $a = ${shift()};
my $key = $fields{shift()};
defined $key or die "Out of band access";
$a->[$key] = shift;
}
- sub FETCH {
+ sub FETCH {
my $a = ${shift()};
my $key = $fields{shift()};
defined $key or die "Out of band access";
Now if $baz is overloaded like this, then C<$bar> is a reference to a
reference to the intermediate array, which keeps a reference to an
actual array, and the access hash. The tie()ing object for the access
-hash is also a reference to a reference to the actual array, so
+hash is also a reference to a reference to the actual array, so
=over
$a = $a->pretty if ref $a;
$b = $b->pretty if ref $b;
"[$meth $a $b]";
- }
+ }
Now one can finish the script by
$a = 'u' unless defined $a;
$b = 'u' unless defined $b;
"[$meth $a $b]";
- }
+ }
Now one can change the last line of the script to
side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
and one can inspect the value in debugger using all the possible
-methods.
+methods.
Something is is still amiss: consider the loop variable $cnt of the
script. It was a number, not an object. We cannot make this value of
} else {
"[$meth $a]";
}
- }
- my %subr = ( n => sub {$_[0]},
- sqrt => sub {sqrt $_[0]},
+ }
+ my %subr = ( n => sub {$_[0]},
+ sqrt => sub {sqrt $_[0]},
'-' => sub {shift() - shift()},
'+' => sub {shift() + shift()},
'/' => sub {shift() / shift()},
);
sub num {
my ($meth, $a, $b) = @{+shift};
- my $subr = $subr{$meth}
+ my $subr = $subr{$meth}
or die "Do not know how to ($meth) in symbolic";
$a = $a->num if ref $a eq __PACKAGE__;
$b = $b->num if ref $b eq __PACKAGE__;
bless [@$self], ref $self;
}
-To make C<++> and C<--> work, we need to implement actual mutators,
+To make C<++> and C<--> work, we need to implement actual mutators,
either directly, or in C<nomethod>. We continue to do things inside
C<nomethod>, thus add
return $obj;
}
-after the first line of wrap(). This is not a most effective
+after the first line of wrap(). This is not a most effective
implementation, one may consider
sub inc { $_[0] = bless ['++', shift, 1]; }
$subr{'++'} = $subr{'+'};
$subr{'--'} = $subr{'-'};
-This finishes implementation of a primitive symbolic calculator in
-50 lines of Perl code. Since the numeric values of subexpressions
+This finishes implementation of a primitive symbolic calculator in
+50 lines of Perl code. Since the numeric values of subexpressions
are not cached, the calculator is very slow.
Here is the answer for the exercise: In the case of str(), we need no
To see it in action, add a method
- sub STORE {
- my $obj = shift;
- $#$obj = 1;
+ sub STORE {
+ my $obj = shift;
+ $#$obj = 1;
@$obj->[0,1] = ('=', shift);
}
interesting effects if some package is not overloaded, but inherits
from two overloaded packages.
-Relation between overloading and tie()ing is broken. Overloading is
+Relation between overloading and tie()ing is broken. Overloading is
triggered or not basing on the I<previous> class of tie()d value.
-This happens because the presence of overloading is checked too early,
+This happens because the presence of overloading is checked too early,
before any tie()d access is attempted. If the FETCH()ed class of the
-tie()d value does not change, a simple workaround is to access the value
+tie()d value does not change, a simple workaround is to access the value
immediately after tie()ing, so that after this call the I<previous> class
coincides with the current one.