What are the differences between parameter input mechanisms in Perl?

When reading a loaded Perl module, I found several ways to determine the input parameters, which are listed below. What are the differences between the two?

sub new{ my $class = shift; my $self = {@_}; bless{$self, $class}; } sub count1{ my ($self, $lab1) = @_; } sub new1{ my ($class, $lab1) = @_; my $self = {}; bless $class, $self; } sub setpath{ my $self = shift; } 
+6
source share
2 answers

When a subroutine is called, the passed parameters are placed in a special @_ array. You can use this array by moving the values my $foo = shift or by directly assigning the array my ($foo,$bar) =@ _; . You can even use values ​​directly from the array: $_[0]

Why is one against the other? Direct array assignment is the most standard and common. Sometimes the shift method is used when there are optional final values. Using a direct array is discouraged, with the exception of a few small niches: wrapper functions that call other functions, especially inside objects. functions that wrap other functions and change inputs. Also a special goto &func form that immediately removes the current call stack and calls func for the current @_ value.

 # use shift for optional trailing values use v5.10; my $foo = shift; my $bar = shift // 'default bar value'; my $baz = shift // 'default baz value'; #obj method to call related non-object function. sub bar { my $self = shift; _bar(@_) } sub longname { shortname(@_) } sub get { return $_[0]->$_[1]; } 
+4
source

# 1 and # 3 are examples of binding an object to a class (Object Oriented Perl).

In # 2, @_ is a list of parameters passed to the function, so $self and $lab1 get the values ​​of the first 2 parameters passed.

Perl has a built-in # 4 shift() routine that takes an array as an argument, and then returns and removes the first element in that array. If it has no argument, it is executed implicitly on @_ . Thus, $self gets the value of the first parameter passed.

+4
source

Source: https://habr.com/ru/post/903952/


All Articles