Can anybody please explain (my $self = shift) in Perl

前端 未结 3 533
长情又很酷
长情又很酷 2021-01-30 22:05

I\'m having a really hard time understanding the intersection of OO Perl and my $self = shift; The documentation on these individual elements is great, but none of

3条回答
  •  遥遥无期
    2021-01-30 22:46

    In top level-code, shift() is short for shift(@ARGV). @ARGV contains the command-line arguments.

    In a sub, shift() is short for shift(@_). @_ contains the sub's arguments.

    So my $self = shift; is grabbing the sub's first argument. When calling a method, the invocant (what's left of the ->) is passed as the first parameter. In other words,

    $o->method(@a)
    

    is similar to

    my $sub = $o->can('method');
    $sub->($o, @a);
    

    In that example, my $self = shift; will assign $o to $self.

提交回复
热议问题