Reputation: 1209
I have a question with the following Code:
#!/usr/bin/perl
use strict;
use warnings;
my %dmax=("dad" => "aaa","asd" => "bbb");
my %dmin=("dad" => "ccc","asd" => "ddd");
&foreach_schleife(\%dmax,\%dmin);
sub foreach_schleife {
my $concat;
my $i=0;
foreach my $keys (sort keys %{$_[0]}) {
while ($_[$i]) {
$concat.="$_[$i]{$keys} ";
print $_[$i]{$keys}."\n";
$i++;
}
$i=0;
$concat="";
}
}
The Output is:
bbb
ddd
aaa
ccc
I don't understand this. Normally you must dereference references on hashes,arrays etc. Why not here? Its enough to write :
$_[$i]{$keys}."\n";
and not something like that:
$$_[$i]{$keys}."\n";
Why?
Has it something to do with the speciality of the variable @_
/$_
?
Upvotes: 3
Views: 905
Reputation: 7579
The reason why you don't have to dereference $_[0]
and $_[1]
is that $_[$i]{$keys}
is a valid short-hand notation for $_[$i]->{$keys}
when your reference is in an array or a hash.
$$_[$i]{$keys}
won't work, because it will try to dereference the special variable $_
to a scalar. The correct syntax is %{$_[$i]}
, but then you'll have to use %{$_[$i]}->{$keys}
, which is more verbose.
Upvotes: 3
Reputation: 29854
My guess is that because an array (or a hash, for that matter) can only contain hash references your second act of indexing means that the reference is understood.
I think the developers need to document this a little better.
To see that it is not special to *_
, you can try this before the loop:
my @a = @_;
And this during:
print $a[$i]{$keys}."\n";
I think the main thing is that if you only have a scalar reference as the base, then at least one ->
is required. So
my ( $damxr, $dminr ) = @_;
would require
$dmaxr->{ $key };
Upvotes: 3
Reputation: 36349
@_
is the array of subroutine arguments, hence $_[$index]
accesses the element at $index
Dereferencing is only good if you have references, but @_
isn't one.
Upvotes: 0