This is tricky because the %fields hash (or any other object) isn't accessible until the statement is successfully executed; i.e., until the ; (semicolon) at the end of the
my %fields = ( ... );
is encountered.
You either have to have all the low-level anonymous hash references prepared before you begin defining the %fields hash, or add them afterward.
It's even more tricky because the other thing to seriously consider is if you really want a copy of the hash reference to a hash with identical content, or a deep copy of the content of that identical hash.
Updates:
-
Added Wikipedia link for "deep copy", some minor wording changes.
-
As an example of what happens when you just make copies of references, consider:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le
"my $hr_same_content = { 1 => 'Ok' };
;;
my %fields = (
version1 => $hr_same_content,
version_TWO => $hr_same_content,
);
print Dumper \%fields;
;;
$fields{version1}{1} = 'Oops...';
;;
print $fields{version_TWO}{1};
"
$VAR1 = {
'version_TWO' => {
'1' => 'Ok'
},
'version1' => $VAR1->{'version_TWO'}
};
Oops...
(The 'version1' => $VAR1->{'version_TWO'} entry in the Dumper listing means that the reference that is the value of the 'version1' key is equal to the reference that is the value of the 'version_TWO' key of the hash.)
So again, do you want to copy content or references to content?
-
If you haven't already, you might want to take a look at the Perl Data Structures Cookbook (or perldoc perldsc from your friendly, local command line).
-
Even pre-defining %fields doesn't help:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le
"my %fields;
%fields = (
version1 => { 1 => 'Ok' },
version_TWO => $fields{version1},
);
print Dumper \%fields;
;;
$fields{version1}{1} = 'Oops...';
;;
print $fields{version_TWO}{1};
"
$VAR1 = {
'version_TWO' => undef,
'version1' => {
'1' => 'Ok'
}
};
Use of uninitialized value in print at -e line 1.
This works:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le
"my %fields = (
version1 => { 1 => 'Ok' },
);
$fields{version_TWO} = $fields{version1};
print Dumper \%fields;
print $fields{version1} {1};
print $fields{version_TWO}{1};
;;
$fields{version1}{1} = 'Oops...';
;;
print $fields{version1} {1};
print $fields{version_TWO}{1};
"
$VAR1 = {
'version_TWO' => {
'1' => 'Ok'
},
'version1' => $VAR1->{'version_TWO'}
};
Ok
Ok
Oops...
Oops...
but, of course, still the problem of copying references.
Give a man a fish: <%-{-{-{-<