2

I am starting to learn Perl, and have questions on the following segment of Perl code.

I know "my" is used to define a local variable, and "shift" is used for getting the head element from an array. What confused me is that where does array come from in the following code segment.

Besides, what does my @positives = keys %{$lab1->{$cate1}}stand for?

preData($cate1, $lab1)

sub preData
{
  my $cate1 = shift;
  my $lab1 = shift;

  my @positives = keys %{$lab1->{$cate1}};
}
CanSpice
  • 34,814
  • 10
  • 72
  • 86
user785099
  • 5,323
  • 10
  • 44
  • 62
  • possible duplicate of [What does shift() do in Perl?](http://stackoverflow.com/questions/296964/what-does-shift-do-in-perl) – a'r Dec 13 '11 at 18:11
  • No, this question is not about what `shift()` is for, it's asking about the hashref dereferencing. The user says they know what `shift()` is for. – CanSpice Dec 13 '11 at 18:17
  • -1 for asking two questions in one posting, causing back-and-forth about which answers/comments go with which question. – tadmc Dec 13 '11 at 18:23

3 Answers3

5

$lab1 is a hash reference containing other hash references. $cate1 is some kind of category key (I'm guessing).

$lab1->{$cate1} is a hash reference. When you dereference it by putting %{ ... } around it, you get a hash back. This hash is then passed to the keys() function, which returns a list of the keys in that hash. Thus @positives is an array of the keys in the hash referenced by the $lab1->{$cate1} hash reference.

Edit: When dealing with these sorts of nested structures, you may find it easier to understand what's going on by seeing a representation of the data. At the top of your script, add use Data::Dumper. Then between the my $lab1... and my @positives... lines, add:

print Dumper($lab1);
print Dumper($lab1->{$cate1});

And after you set the @positives array, add:

print Dumper(\@positives);

This should allow you to better visualize the data and hopefully get a better understanding of Perl structures.

CanSpice
  • 34,814
  • 10
  • 72
  • 86
2

When you call a subroutine in Perl, the arguments to that subroutine are passed to it in the @_ array. Calling shift without any parameters will take its arguments from the @_ array. So this code is taking $cate1 from the first parameter to preData and $lab1 from the second parameter to preData.

David Brigada
  • 594
  • 2
  • 10
2

@ denotes an array and % denotes a hash. So this statement:

my @x = keys %y;

Means take the list of keys from the hash y and assign them to the array x. I.e., if %y is:

one => 1,
two => 2,
three => 3

Then @x would contain:

one, two, three
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98