use strict; use warnings; # Use this to show the data structure. # use Data::Dumper; # Initialise a hash reference and a sequence no. # my $rhPreserve = {}; my $insertionOrder = 0; # Read our data line by line, chomping off the newline # and splitting on the ":" and using the colour name # as the key and RGB for the value. # while() { chomp; my ($value, $key) = split /:/; # Make an entry in the hash reference for this colour but # the value is another hash with two key/value pairs, one # for our RGB value and the other the insertion order # which we increment after insertion. # $rhPreserve->{$key} = { value => $value, insertionOrder => $insertionOrder ++ }; } # Use Data::Dumper to print out the hash reference so we can see # what we have constructed. The colour "keys" will come out in an # order determined by the underlying hashing algorith. # my $dd = Data::Dumper->new([$rhPreserve], ["rhPreserve"]); print "Data structure\n", $dd->Dumpxs(); # To use our insertion order, which we have preserved in the hash # reference, we can sort by "insertionOrder" then use the sorted keys # to access the hash reference. # my @keysInInsertionOrder = sort { $rhPreserve->{$a}->{insertionOrder} <=> $rhPreserve->{$b}->{insertionOrder} } keys %$rhPreserve; print "Data in insertion order\n"; foreach (@keysInInsertionOrder) { print "Insertion order - $rhPreserve->{$_}->{insertionOrder}\n", " Key - $_\n", " Value - $rhPreserve->{$_}->{value}\n"; } __END__ 255 250 250:snow 248 248 255:GhostWhite 245 245 245:WhiteSmoke 220 220 220:gainsboro 255 250 240:FloralWhite 253 245 230:OldLace 250 240 230:linen 250 235 215:AntiqueWhite 255 239 213:PapayaWhip 255 235 205:BlanchedAlmond 255 228 196:bisque 255 218 185:PeachPuff 255 222 173:NavajoWhite 255 228 181:moccasin 255 248 220:cornsilk 255 255 240:ivory 255 250 205:LemonChiffon 255 245 238:seashell 240 255 240:honeydew