I have this piece of code that I'm trying to get my head around, I don't even know if its syntactically correct (part of the exercise I guess!)
%{$records}
What do the curly braces signify? I've seen the same case but with a @
operator used instead of the $
if that makes a difference.
Thanks guys!
The “Using References” section of the perlref documentation explains.
2. Anywhere you’d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this:
$bar = ${$scalarref}; push(@{$arrayref}, $filename); ${$arrayref}[0] = "January"; ${$hashref}{"KEY"} = "VALUE"; &{$coderef}(1,2,3); $globref->print("output\n"); # iff IO::Handle is loaded
In your case, $records
must be a reference to a hash (because of the outermost %
), {$records}
is a block that returns the reference, and %{$records}
gives the original hash.
The curly braces surround a bona fide block. In fact, you could replace the code above with
%{ if ($records) { $records } else { $default_records } }
But even the shorter version from your question could be simplified, as pointed out earlier in the documentation.
1. Anywhere you’d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type:
$bar = $$scalarref; push(@$arrayref, $filename); $$arrayref[0] = "January"; $$hashref{"KEY"} = "VALUE"; &$coderef(1,2,3); print $globref "output\n";
Because $records
is a simple scalar, %$records
is the underlying hash.
If instead $records
were a reference to an array, the syntax for dereferencing it would be @$records
or @{$records}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With