Question

While reading a downloaded Perl module, I found several ways of defining input parameters, which are listed as following. What are the differences between them?

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;
}
Was it helpful?

Solution

When a subroutine is called, the passed parameters are put into a special array @_. One can consume this array by shifting values out my $foo = shift or by direct array assignment my ($foo,$bar)=@_; It is even possible to use the values directly from the array: $_[0]

Why one versus the others? Direct array assignment is the most standard and common. Sometimes the shift way is used when there are optional trailing values. Direct array usage is discouraged except in few small niches: wrapper functions that are calling other functions, especially inside of objects. functions that wrap other functions and and modify the inputs. Also the special form of goto &func which immediately drops the current call stack and calls func on the current value of @_.

# 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]; }

OTHER TIPS

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

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

In #4, shift() is a built in Perl subroutine that takes an array as an argument, then returns and deletes the first item in that array. If it has no argument, it is executed implicitly on @_. So $self gets the value of the first passed parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top