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


In reply to text-file parsing with automatic field ordering by 0xbeef

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.