Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

perl - dynamically add leading underscore to existing sub

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;
}
question from:https://stackoverflow.com/questions/65645504/dynamically-add-leading-underscore-to-existing-sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

_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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...