user1855888
user1855888

Reputation: 141

What does "my ($self, %myInputs) = @_;" mean?

I came across this line a lot of times in perl modules but I could not figure out what this exactly means.

my ($self, %myInputs) = @_;

Kindly explain me the statement so that I can proceed.

Upvotes: 8

Views: 7065

Answers (3)

aurelien
aurelien

Reputation: 423

In Perl @_; is a Global Array Special Variables

Similar as @ARGV The array contain the command-line arguments intended for the script.

So in my ($self, %myInputs) = @_;

@_ would represent the argument of the Variable $ in the Hash-Variables %

Upvotes: 1

Evan Carroll
Evan Carroll

Reputation: 1

my ($self, %myInputs) = @_;

Not all functions receive the first argument $self. In fact, by convention, only the ones invoked using the arrow operator do ->; invoking with -> implicitly sends a special argument referring to the object. All functions and methods in perl are declared the same way (using keyword sub). Only invocation determines whether or not the function is a method.

The my ($foo, $bar) = ( $x, $y ); is called parallel assignment. That's all that is going on here!

Observe a hash can be initialized from an array in Perl.

my @foo = qw/ foo bar baz quz /;
my %hash = @foo;
print $hash{foo}; # outputs bar

Because you're assigning to the hash %myInputs, the hash is explicitly assigned all inputs that are not the implicitly sent (because you're pulling that one off into $self). But be careful, it wouldn't make much sense to do the following right?

my @foo = qw/ foo bar baz /;
my %hash = @foo;
print $hash{baz} # what is this set too??

For the same reason, it also doesn't make much sense to invoke your function with an un-even amount of arguments! Both will generate a warning.

Upvotes: 6

Karthik T
Karthik T

Reputation: 31952

Im guessing that is one of the first lines in a class method function. That line parses @_ which is the list of the function arguements, and extracts the first param which is always a reference to the object into $self and extracts the rest of them into a hash %myInputs. This ofcourse assumes that the function is called with the arguements in hash format, like in the below Perl/Tk function

$mw->Button(-text => "RIGHT", -command => sub { exit })
  ->pack(-side => 'right', -fill => 'both');

Upvotes: 8

Related Questions