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?

Miller
  • 34,962
  • 4
  • 39
  • 60
  • 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 '14 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? – stan saltys Aug 21 '14 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 '14 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]? – stan saltys Aug 21 '14 at 15:32
  • Yes, correct. btw, if coming from Ruby you might be interested in [perl5i module](http://search.cpan.org/~mschwern/perl5i-v2.13.0/lib/perl5ifaq.pod) – mpapec Aug 21 '14 at 15:38
  • Thank You. I will go ahead and check that out. – stan saltys Aug 21 '14 at 15:42
  • If you want to do a little less typing you can do `$self->doSomething(record => $record, listing => [$foo, $bar, $baz]);` Then, in doSomething, have `my ($self, %args) = @_; $args{record};` – marneborn Aug 21 '14 at 15:46

1 Answers1

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};
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335