M
marcin-usenet
See the following test program. I expected that to print "666" four
times. However it does it three times, and then says Use of
uninitialized value in print at ./test line 56.
Can anyone explain why? Noone felt like explaining in #perl on
freenode. :-(
regards
Marcin
#!/usr/bin/perl -w
use strict;
package Base;
sub new
{
my $that = shift;
my $class = ref $that || $that;
my $self = {};
bless $self, $class;
return $self;
}
use vars '$AUTOLOAD';
sub AUTOLOAD
{
my $self = shift;
my $name = $AUTOLOAD;
$name =~ s,.*:,,;
# scalar mutator
return $self->{$name} = shift if @_;
# accessor
return $self->{$name};
}
package Hash;
use base 'Base';
package Container;
use base 'Base';
sub setting_with_shift
{
my $self = shift;
wantarray ? map { $self->settings->{$_} } @_ :
$self->settings->{shift};
}
sub setting_without_shift
{
my $self = shift;
wantarray ? map { $self->settings->{$_} } @_ :
$self->settings->{$_[0]};
}
package main;
my $h = Hash->new;
$h->foo(666);
my $c = Container->new;
$c->settings($h);
print $c->setting_without_shift('foo');
print "\n";
print $c->setting_with_shift('foo');
print "\n";
print scalar $c->setting_without_shift('foo');
print "\n";
print scalar $c->setting_with_shift('foo');
print "\n";
times. However it does it three times, and then says Use of
uninitialized value in print at ./test line 56.
Can anyone explain why? Noone felt like explaining in #perl on
freenode. :-(
regards
Marcin
#!/usr/bin/perl -w
use strict;
package Base;
sub new
{
my $that = shift;
my $class = ref $that || $that;
my $self = {};
bless $self, $class;
return $self;
}
use vars '$AUTOLOAD';
sub AUTOLOAD
{
my $self = shift;
my $name = $AUTOLOAD;
$name =~ s,.*:,,;
# scalar mutator
return $self->{$name} = shift if @_;
# accessor
return $self->{$name};
}
package Hash;
use base 'Base';
package Container;
use base 'Base';
sub setting_with_shift
{
my $self = shift;
wantarray ? map { $self->settings->{$_} } @_ :
$self->settings->{shift};
}
sub setting_without_shift
{
my $self = shift;
wantarray ? map { $self->settings->{$_} } @_ :
$self->settings->{$_[0]};
}
package main;
my $h = Hash->new;
$h->foo(666);
my $c = Container->new;
$c->settings($h);
print $c->setting_without_shift('foo');
print "\n";
print $c->setting_with_shift('foo');
print "\n";
print scalar $c->setting_without_shift('foo');
print "\n";
print scalar $c->setting_with_shift('foo');
print "\n";