import-bot (20211) [Avatar] Offline
#1
[Originally posted by ctxica]

Mr. Johnson:

On page 146 I’m a little confused on how to relate to the list below to the
code:
$students{$fields[0]} [$fields[1] ] = $fields[2];
$students{fields[0]} [0] +- $fields[2];

Bill Jones:2:35
Ann Smith:3:41
Sara Tims:2:45
Bill Jones:1:42
Anne Smith:1:42
Sara Tims:1:41
Anne Smith:2:47
Bill Jones3:41

Can you explain that for me.
import-bot (20211) [Avatar] Offline
#2
Re: references
[Originally posted by jandrew]

> On page 146 I?m a little confused on how to relate to the list below to the
> code:
> $students{$fields[0]} [$fields[1] ] = $fields[2];
> $students{fields[0]} [0] +- $fields[2];
>
> Bill Jones:2:35
> Ann Smith:3:41
> Sara Tims:2:45
> Bill Jones:1:42
> Anne Smith:1:42
> Sara Tims:1:41
> Anne Smith:2:47
> Bill Jones3:41

Well, let's look at the whole loop that builds the data structure:

my %students;
while( <DATA> ) {
chomp;
my @fields = split /:/;
$students{$fields[0]}[$fields[1]] = $fields[2];
$students{$fields[0]}[0] += $fields[2];
}

Now, line by line in the loop: first we chomp off the newline of the
line just read in, then we split the line into an array by splitting
on the colon character - so, for the first line of data our @fields
array holds: ('Bill Jones', 2, 35).

Now, our student hash uses the names for keys and we use an anonymous
array reference as the value -- but we create it via autovivification
which means that if we dereference it and assign to as if it were an
array reference, Perl creates that array reference for us. Let's
consider what we build with the first data line:

$students{$fields[0]}[$fields[1]] = $fields[2];
$students{$fields[0]}[0] += $fields[2];

really is saying:

$students{'Bill Jones'}[2] = 35;
$students{'Bill Jones'}[0] += 35;

So, the value for the key 'Bill Jones' is an anonymous array that
looks like: [35, undef, 35]. Now, when we read the 4th data line
(the next 'Bill Jones' line in the file) we are making the following
assignments:

$students{'Bill Jones'}[1] = 42;
$students{'Bill Jones'}[0] += 42;

So, we've now assigned 42 to index 1, and added it to index 0 and our
anonymous array for 'Bill Jones' is now: [77, 42, 35], and after
reading in the third 'Bill Jones' line it will be: [118, 42, 35, 41].

The diagram on page 148 shows graphically what the whole data
structure looks like after reading in all the lines.

I hope this clarifies things a little ... if not then ask again and
I'll have another go at it.

regards,
andrew