Is there a difference between Perl's shift versus assignment from @_ for subroutine parameters?

后端 未结 9 1538
刺人心
刺人心 2020-12-14 20:16

Let us ignore for a moment Damian Conway\'s best practice of no more than three positional parameters for any given subroutine.

Is there any difference between the t

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 20:31

    The best way, IMHO, is a slight mixture of the two, as in the new function in a module:

    our $Class;    
    sub new {
        my $Class = shift;
        my %opts = @_;
        my $self = \%opts;
        # validate %opts for correctness
        ...
        bless $self, $Class;
    }
    

    Then, all calling arguments to the constructor are passed as a hash, which makes the code much more readable than just a list of parameters.

    Plus, like brian said, the @_ variable is unmodified, which can be useful in unusual cases.

提交回复
热议问题