7

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.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
user1855888
  • 131
  • 2
  • 5

3 Answers3

8

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');
Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
6

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.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • But what is the need of using $self! It just confuses me so much! – user1855888 Dec 27 '12 at 15:13
  • 1
    @user1855888 `$self` refers to the object you're calling on. If you call `my $a Animal->new`, and then you call `$a->run` then `$self` (first argument) inside of `sub run {}` would be set to `$a`. In other languages you call it `this`. You can call it `$this` in Perl too if you're used to that, `my $this = shift` (though it's against convention). – Evan Carroll Dec 27 '12 at 16:46
1

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 %

aurelien
  • 404
  • 4
  • 22