Reputation: 5563
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}};
}
Upvotes: 2
Views: 129
Reputation: 53636
@ 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
Upvotes: 2
Reputation: 594
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.
Upvotes: 2
Reputation: 35828
$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.
Upvotes: 5