in reply to split to hash, problem with random keys

Maybe you don't want a hash at all:
#!/usr/bin/perl use constant FIRSTNAME => 0; use constant LASTNAME => 1; use constant ADDRESS => 2; while (<>) { chomp; my @iRecord=split(/\|/); print "Address for $iRecord[FIRSTNAME] $iRecord[LASTNAME] is $iRecor +d[ADDRESS]\n"; }
This works with an input file like
First|User|123 Some Street.
Second|Person|123 Some Street.
Third|Guy|456 Other Street
Fourth|Lady|456 Other Street
You just have to set the constants to correspond to the order of the fields in the input file, and that's all that has to change if the file format changes. Perl should evaluate the constants at compile-time and arrays are faster to access than hashes, so this should be somewhat faster than your current solution too (although you'd need to benchmark to know for sure). Edit: Changed names in sample data.

Replies are listed 'Best First'.
Re: Re: split to hash, problem with random keys
by december (Pilgrim) on Jul 04, 2003 at 13:37 UTC

    That's a nice solution. I use the hash everywhere already, so I am a bit reluctant to switch now, but I will keep this in mind for other applications... Thanks!