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:
_init()
?@$
syntax mean when writing @$self{keys %extra} = values %extra;
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.
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.
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.
Your understanding is correct. This allows the user of a class to set any parameters they want into the object.
Yes. If you call, for example, $myobject->_init('color', 'green')
, then this code will set $myobject->{'color'} = 'green'
.
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};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With