in reply to How to make a reference to a hash cell

I agree with hippo that the keys of the %catalog hash make a decent reference, and that's probably how I would have done it, although those "references" are only like symbolic references. If you want to use "hard" references and have everything stored in one data structure, that's possible too, although there is a caveat: If you store the values of %catalog as elements of the $student{$student_id} array, you lose the key (the course number). One common solution is to additionally store the key as part of the value (often a hash reference). In the following, I'm using the property of Foreach Loops that the loop iterator variable is an alias, so that I can overwrite elements of the array by assigning to the iterator variable.

use warnings; use strict; use Data::Dump; my %expensive_lookup = ( math01 => { instructor=>'alice' }, sci99 => { instructor=>'bob' }, gym55 => { instructor=>'carol' }, cs101 => { instructor=>'larry' }, ); my %students = ( sid01 => [qw/ math01 gym55 /], sid007 => [qw/ gym55 sci99 /], sid42 => [qw/ cs101 math01 /], ); my %catalog = (); for my $student_id (keys %students) { for my $course_number ( @{ $students{$student_id} } ) { if ( not exists $catalog{$course_number} ) { $catalog{$course_number} = $expensive_lookup{$course_number}; $catalog{$course_number}{course_number} = $course_number; } $course_number = $catalog{$course_number}; } } dd \%catalog, \%students; __END__ do { my $a = { cs101 => { course_number => "cs101", instructor => "larry" }, gym55 => { course_number => "gym55", instructor => "carol" }, math01 => { course_number => "math01", instructor => "alice" }, sci99 => { course_number => "sci99", instructor => "bob" }, }; ( $a, { sid007 => [$a->{gym55}, $a->{sci99}], sid01 => [$a->{math01}, $a->{gym55}], sid42 => [$a->{cs101}, $a->{math01}], }, ); }

Replies are listed 'Best First'.
Re^2: How to make a reference to a hash cell
by ibm1620 (Hermit) on Apr 30, 2018 at 15:06 UTC
    Thanks - good illustration.

    (Never heard of Data::Dump -- much nicer than Dumper.)