K
kj
I recently came across the following (somewhat tongue-in-cheek) Perl
code.
#!/usr/bin/perl -w
use strict;
BEGIN
{
package True;
use overload
'eq' => \&equals,
'==' => \&equals,
bool => sub { !!1 },
'!' => sub { False->new() },
;
use base 'Exporter';
our @EXPORT = qw( &TRUE );
sub new
{
my ($class) = @_;
my $self = 1;
return bless \$self, $class;
}
sub TRUE
{
return True->new();
}
sub equals
{
my ($x, $y, $swap) = @_;
$y ? True->new() : False->new();
}
}
BEGIN
{
package False;
use overload
'eq' => \&equals,
'==' => \&equals,
bool => sub { !!0 },
'!' => sub { True->new() },
;
use base 'Exporter';
our @EXPORT = qw( FALSE );
sub new
{
my ($class) = @_;
my $self = 0;
return bless \$self, $class;
}
sub FALSE
{
return False->new();
}
sub equals
{
my ($x, $y, $swap) = @_;
return $y ? False->new() : True->new();
}
}
BEGIN
{
import True;
import False;
}
my $n;
BEGIN { $n = 0 }
use Test;
plan tests => $n;
BEGIN { $n += 2 }
ok TRUE;
ok not FALSE;
# several more tests omitted from the original
__END__
I have some questions about this code:
1. Why do the equals subs have a third (unused) argument $swap?
2. In this case, what would be the difference between "import True;"
and "use True;"? Is "import True;" equivalent to
"True->import();"? And why are the import statements placed inside
a BEGIN block?
Thanks,
kj
code.
#!/usr/bin/perl -w
use strict;
BEGIN
{
package True;
use overload
'eq' => \&equals,
'==' => \&equals,
bool => sub { !!1 },
'!' => sub { False->new() },
;
use base 'Exporter';
our @EXPORT = qw( &TRUE );
sub new
{
my ($class) = @_;
my $self = 1;
return bless \$self, $class;
}
sub TRUE
{
return True->new();
}
sub equals
{
my ($x, $y, $swap) = @_;
$y ? True->new() : False->new();
}
}
BEGIN
{
package False;
use overload
'eq' => \&equals,
'==' => \&equals,
bool => sub { !!0 },
'!' => sub { True->new() },
;
use base 'Exporter';
our @EXPORT = qw( FALSE );
sub new
{
my ($class) = @_;
my $self = 0;
return bless \$self, $class;
}
sub FALSE
{
return False->new();
}
sub equals
{
my ($x, $y, $swap) = @_;
return $y ? False->new() : True->new();
}
}
BEGIN
{
import True;
import False;
}
my $n;
BEGIN { $n = 0 }
use Test;
plan tests => $n;
BEGIN { $n += 2 }
ok TRUE;
ok not FALSE;
# several more tests omitted from the original
__END__
I have some questions about this code:
1. Why do the equals subs have a third (unused) argument $swap?
2. In this case, what would be the difference between "import True;"
and "use True;"? Is "import True;" equivalent to
"True->import();"? And why are the import statements placed inside
a BEGIN block?
Thanks,
kj