1

I'm working through some sample code, and I'm trying to figure out why it works with the brackets around $args. Without it, I don't get the values.

sub random_dice{
  my ($args) = @_;
  my $number_of_rolls = $args->{number_of_rolls} || 6;
  ...
}

# I don't understand why it works with the brackets around $args
my $r = random_dice({number_of_rolls=>5});
ikegami
  • 367,544
  • 15
  • 269
  • 518
airnet
  • 2,565
  • 5
  • 31
  • 35

3 Answers3

5

It works because you are passing an anonymous hash to your random_dice subroutine.

my ($args) = @_; # sets $args as element of @_. Not as an array

$args is now a reference to a hash

$args = {
   number_of_rolls => 5
};

This is generally used as a method to have named parameters in Perl

Nate
  • 1,889
  • 1
  • 20
  • 40
3

Like this:

my $args = @_;

the assignment is made in scalar context, so $args is assigned the value 1 (the number of elements in the array).

But like this:

my ($args) = @_;

the assignment is made in list context. The values from the array on the right side are unpacked and assigned to elements of the array on the left side.

Brian
  • 15,599
  • 4
  • 46
  • 63
2

If you want to use the simpler

my $r = random_dice( number_of_rolls => 5 );

the sub would have to be changed to

sub random_dice{
  my %args = @_;
  my $number_of_rolls = $args{number_of_rolls} || 6;
  ...
}
ikegami
  • 367,544
  • 15
  • 269
  • 518