Search code examples
perlargshashref

Perl args and defining it


Hello I am trying to understand Perl better. I come from Ruby and trying to wrap my head around Perl for fun. Let's say I have this code block here.

$self->doSomething(
    {   record     => $record,
        listing    => [ $foo, $bar, $baz ],
        passedargs => { something => $val, another => $val2 },
    }
);

What exactly is defined as $args? My thought process from reading Perl docs is something like my ($self, $args) = @_; Meaning everything within the doSomething block is considered $args and if I wanted to access it. I would my $args = @_[0];

Just curious if I am thinking about this correctly? if not care to explain?


Solution

  • Since you are invoking doSomething as a method call, the first argument will be the object you are calling the method on (i.e. that which is on the left hand side of the arrow operator: $self).

    The second argument will be the hashref you are passing between the ( and the ).

    You access a particular member of the hashref just as you would for any other hashref.

    sub doSomething {
        my ($self, $args) = @_;
        my $record = $args->{record};