http://qs321.pair.com?node_id=618456

0xbeef has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed monks,

I have somehow managed to produce the following code (derived in part from Using variable names from an array), which uses the first commented line of an input file to determine the order of the data records that follow.

This means I do not have to make code changes when the file layout changes since I can simply adjust the commented header according the new data layout. i.e. a new file format of #category:surname:name will just automagically work...

#!/usr/bin/perl -w use strict; my %index; my @array; my $headerline = <DATA>; chomp $headerline; $headerline =~ s/^#//; my @header = split /:/,$headerline; @index{@header} = (0..$#header); while (<DATA>) { chomp; my @fields = split /:/,$_; for my $key (keys %index) { $array[$. - 1]{$key} = $fields[$index{$key}]; } } # examples print "1st name : $array[1]{'name'}\n"; print "3rd category : $array[3]{'category'}\n"; # traverse entire array for my $row (1..$#array) { print "Row $row: "; for my $keyname (keys %index) { print "$keyname=$array[$row]{$keyname} "; } print "\n"; } __DATA__ #name:surname:category tiger:woods:golfer tyler:hamilton:f1 james:stewart:supercross roger:federer:tennis

which produces

1st name : tiger 3rd category : supercross Row 1: name=tiger category=golfer surname=woods Row 2: name=tyler category=f1 surname=hamilton Row 3: name=james category=supercross surname=stewart Row 4: name=roger category=tennis surname=federer
Is this type of referencing okay or insane, or is there mayber a simpler/better/faster way? (First prize = without using any external module)

I do understand that the script lacks some error handling, but the question is more about the referencing...

Niel