In this example for perl book, where is "_components" coming from? I know adding _ to indicate sub is private to the package but this one seems to use leading score out of nowhere. Can you please point me to some source about this? thank you.
package Computer;
@ISA = qw(StoreItem);
sub new {
my $pkg = shift;
my $obj = $pkg->SUPER::new("Computer", 0,0);
$obj->{_components} = [];
$obj->components(@_);
$obj;
}
sub components {
my $obj = shift;
@_ ? push (@{$ojb->{_components}}, @_) : @{$obj->{_components}};
}
sub price {
my $obj = shift;
my $price = 0;
my $component;
for my $component ($obj->components()) {
$price += $component->price();
}
$price;
}
_components
is a literal key for the $obj
hash reference. It is not "coming from" anywhere. This is a quirk of Perl syntax. In the statement
$obj->{_components} = [];
$obj
is a reference to a newly created instance of a class (in the prior statement) and _components
is being defined as a key in that instance, and being initialized to a reference to an empty array. This is equivalent to
$obj->{'_components'} = [];
For instance
$ perl -de0
Loading DB routines from perl5db.pl version 1.55
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(-e:1): 0
DB<1> $obj->{a} = "hello";
DB<2> x $obj
0 HASH(0x800756bf8)
'a' => 'hello'
DB<3> p $obj->{'a'}
hello
DB<4> p $obj->{a}
hello
DB<5>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With