Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sub _init in Perl explanation

Tags:

perl

I was wondering what this subroutine does in Perl. I believe i have the general idea but i'm wondering about some of the syntax.

sub _init 
{
  my $self = shift;
  if (@_) {
    my %extra = @_;
    @$self{keys %extra} = values %extra;
  }
}

Here is what i think it does: essentially add any "extra" key-value pairs to the nameless hash refereced by the variable $self. Also i'm not 100% sure about this but i think my $self = shift is actually referring to the variable $self that called the _init() subroutine.

My specific questions are:

  1. Is $self actually referring to the variable that called the subroutine _init() ?
  2. What does the @$ syntax mean when writing @$self{keys %extra} = values %extra;
like image 551
rage Avatar asked Sep 18 '13 17:09

rage


People also ask

What is subroutine in Perl explain with suitable example?

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.

What does sub mean in Perl?

A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.

What is subroutine in Perl explain passing arguments to subroutine?

You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.


1 Answers

Your understanding is correct. This allows the user of a class to set any parameters they want into the object.

  1. Yes. If you call, for example, $myobject->_init('color', 'green'), then this code will set $myobject->{'color'} = 'green'.

  2. This is a somewhat confusing hash operation. keys %extra is a list (obviously of keys). We are effectively using a "hash slice" here. Think of it like an array slice, where you can call @$arrayref[1, 3, 4]. We use the @ sign here because we're talking about a list - it's the list of values corresponding to the list of keys keys %extra in the hash referenced by $self.

Another way to write this would be:

foreach my $key (keys %extra) {
  $self->{$key} = $extra{$key};
}
like image 171
Dan Avatar answered Oct 04 '22 21:10

Dan