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

Greetings Monks, I am trying to grab a bunch of variables from a fixed width file. I have only tried doing it one way so far, it seems to be working okay but is a little unpredictable. Here is how I am doing it now: First I grab a key from a work file, this key will tell me which record to grab from the control file with the variables. They key is held between two astericks at the top of a data file.
sub get_key { open (FOO_TEXT, '/tmp/foo.work')or die "Could not open work file $!\n +"; while (<FOO_TEXT>) { if (/\*([^*]+)\*/) { my $key = $1; get_foocf($key); }
Then I call the sub to grab the line matching the key from the control file:
sub get_foocf { my $key = shift; open (FOO_CF, '/tmp/foocf.dat') or die "Control file unavailable $!"; while (<FOO_CF>) { if (/$key/) { } my $foo_opts = ($'); get_foo_opts($foo_opts); }
Then I take the line grabbed from the control file and turn it into an array where I will grab my variables.
sub get_domopts { my $foo_opts=shift; my @foo_opts = split ( //, $foo_opts ); my $cvtype = $dom_opts[0]; my $cvnumber = join ( "", @foo_opts[ 1 .. 10 ] ); my $dtype = join ( "", @foo_opts[ 11, 12 ] ); my $cdir = join ( "", @foo_opts[ 13 .. 15 ] ); my $dp = join ( "", $foo_opts[16] ); my $dpform = join ( "", @foo_opts[ 17, 18 ] ); my $dpnc = join ( "", $foo_opts[19] ); my $dprntr = join ( "", @foo_opts[ 20 .. 23 ] ); my $dpfill = join ( "", @foo_opts[ 24 .. 73 ] ); my $de = join ( "", $foo_opts[74] ); my $deform = join ( "", @foo_opts[ 75, 76 ] ); my $deadd = join ( "", @foo_opts[ 77 .. 176 ] ); my $defill = join ( "", @foo_opts[ 177 .. 226 ] ); }
I have a few questions about this: 1. Is this this the best way to do this ( I doubt it is )? 2. If this is not the best way to do this , what would be the best way? I want to be ablt to have access to all of the variable from several subroutines in the program. 3. The variables are all different some text some numbers, what is the best way to reference the individual indices:
@foo[2]
or
$foo[2]
I know it really depends on the context, so lets just say all I care about is the text and will not be doing a great deal of conditionals with the indices. I hope this made sense I am just trying to get a better understanding of how to grab variables from external data sources. Thanks in advance for any help ! It is always appreciated. -Aseidas-

Replies are listed 'Best First'.
Re: creating variables from a fixed width file
by BrowserUk (Patriarch) on Jul 02, 2002 at 16:01 UTC

    You might want to look at perlvar for the $/ (input record seperator) especially setting this to a reference to a number e.g.$/ = \266; assuming your fixed records are 226 byte in length.

    And then look at unpack() for a cleaner way of extracting the fields.

Re: creating variables from a fixed width file
by particle (Vicar) on Jul 02, 2002 at 17:22 UTC