I have this syntax in a perl script and I don't know what it means:
$string.= "$$info{$id}{free}\t";
.
I am very new to pearl (first time reading a perl script) and I didn't find any useful information for this.
CodePudding user response:
$info
is a hash reference. This refers to a multi level data structure, with the first level key set by another variable $id
. Your structure might look something like this:
my $info = {
1 => {
free => 2,
used => 3,
},
2 => {
free => 1,
used => 0,
},
};
The $id
in this example would be 1
or 2
.
You can read about this in more detail in perlreftut.
Your code takes the value from inside the data structure and appends it to a variable $string
followed by a tab character. It looks like it's building a tab separated file, similar to a CSV file.
CodePudding user response:
As per Perl Dereferencing Syntax, $$info{ $id }
can also be written as $info->{ $id }
. (I'm not alone in finding the latter much clearer.)
$info->{ $id }{ free }
is short for
$info->{ $id }->{ "free" }
This is just just following two hash element dereferences chained into a single expression:
my $anon = $info->{ $id }; $anon->{ "free" }
HASHREF->{ KEY }
is used to get the value of a hash element given a reference to a hash and the key of the element.
This means that $info
is expected to be a reference to a hash. $info->{ $id }
gets the value of the element with the value of $id
for key.
Similarly, $info->{ $id }
/$anon
is expected to be a reference to a hash. $anon->{ "free" }
gets the value of the element with key free
.
For example,
my $info = {
machine01 => {
free => 100,
used => 200,
},
machine02 => {
free => 50,
used => 450,
},
};
my $id = "machine01";
say $info->{ $id }{ free }; # 100
See perlreftut