perl/lib/overloading.pm
James Raspass 176b7241c8 Modernise overloading pragma a little
- Move the version declaration into the package line.
 - Use v5.40 to get strict, warnings, and the module_true feature.
 - Make private sub lexical, it's unlikely to be used in darkpan.
 - Make use of subroutine signatures.
2025-09-17 09:31:59 -06:00

92 lines
1.7 KiB
Perl

package overloading 0.03;
use v5.40;
my $HINT_NO_AMAGIC = 0x01000000; # see perl.h
my sub ops_to_nums (@ops) {
require overload::numbers;
map { exists $overload::numbers::names{"($_"}
? $overload::numbers::names{"($_"}
: do { require Carp; Carp::croak("'$_' is not a valid overload") }
} @ops;
}
sub import ($, @ops) {
if ( @ops ) {
if ( $^H{overloading} ) {
vec($^H{overloading} , $_, 1) = 0 for ops_to_nums(@ops);
}
if ( $^H{overloading} !~ /[^\0]/ ) {
delete $^H{overloading};
$^H &= ~$HINT_NO_AMAGIC;
}
} else {
delete $^H{overloading};
$^H &= ~$HINT_NO_AMAGIC;
}
}
sub unimport ($, @ops) {
if ( exists $^H{overloading} or not $^H & $HINT_NO_AMAGIC ) {
if ( @ops ) {
vec($^H{overloading} ||= '', $_, 1) = 1 for ops_to_nums(@ops);
} else {
delete $^H{overloading};
}
}
$^H |= $HINT_NO_AMAGIC;
}
__END__
=head1 NAME
overloading - perl pragma to lexically control overloading
=head1 SYNOPSIS
{
no overloading;
my $str = "$object"; # doesn't call stringification overload
}
# it's lexical, so this stringifies:
warn "$object";
# it can be enabled per op
no overloading qw("");
warn "$object";
# and also reenabled
use overloading;
=head1 DESCRIPTION
This pragma allows you to lexically disable or enable overloading.
=over 6
=item C<no overloading>
Disables overloading entirely in the current lexical scope.
=item C<no overloading @ops>
Disables only specific overloads in the current lexical scope.
=item C<use overloading>
Reenables overloading in the current lexical scope.
=item C<use overloading @ops>
Reenables overloading only for specific ops in the current lexical scope.
=back
=cut