Please explain me what is hapenning in line 3 of this code.
for my $i (0 .. $dim) {
for my $j (0 .. $dim) {
$adj->[$i][$j] = $adj->[$i][$j] ? [$j] : [];
Please explain me what is hapenning in line 3 of this code.
for my $i (0 .. $dim) {
for my $j (0 .. $dim) {
$adj->[$i][$j] = $adj->[$i][$j] ? [$j] : [];
The code loops over two dimensions in an array reference $adj
. Presumably, $dim
is the dimension, and $i
and $j
iterate over a list of numbers from 0
to $dim
, e.g. 0,1,2,3,4,5
.
For each combination of numbers, the value of that array element is checked for trueness, and is assigned a new value. If the value is false, it is assigned an array ref containing the index $j
, otherwise an empty array ref []
.
The conditional operator is used here, with the basic syntax
CONDITION ? FOO : BAR
if CONDITION then FOO else BAR
Presumably, the array ref $adj
is supposed to contain array references, which is why it can simply check for trueness as a shortcut for defined $adj->[$i][$j]
.
This is the ternary operator, aka conditional operator.
If $adj->[$i][$j]
is 0 (or undefined) then []
is assigned to $adj->[$i][$j]
, in the other cases $adj->[$i][$j]
is assigened to $adj->[$i][$j]
.
perlop has this quote:
Ternary "?:" is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned.
for my $i (0 .. $dim) {
for my $j (0 .. $dim) {
Above for loops will itrate through the arry with dimension $dim x $dim
$adj->[$i][$j] = $adj->[$i][$j] ? [$j] : [];
if $adj->[$i][$j] is zero, then assign [] to $adj->[$i][$j] else assign $j (column value)