1

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?

7
  • 2
    Since $self->doSomething is method call, first argument to method ($_[0]) is always object itself, and rest of them are parameters ($_[1], etc.). In this case $arg is hash reference from $_[1].
    – mpapec
    Aug 21, 2014 at 15:22
  • "In this case $arg is hash reference from $_[1]" So this means $arg is a hash reference of the values record, listing and passedargs? being the keys? Aug 21, 2014 at 15:24
  • First you assign input parameters my ($self, $args) = @_; and then $args->{record} to access value of $record ($_[1]{record} would be the same thing but much less readable).
    – mpapec
    Aug 21, 2014 at 15:28
  • 1
    Thank you, this is starting to clear up things for me. I really appreciate it. So just one more example if I wanted to just access bar inside of listings. I would $args->{listing}[1]? Aug 21, 2014 at 15:32
  • Yes, correct. btw, if coming from Ruby you might be interested in perl5i module
    – mpapec
    Aug 21, 2014 at 15:38

1 Answer 1

3

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};
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.