Friday, January 11, 2002, 3:12:19 PM, Scott wrote:

> I am reading a file into a list and then formatting it to prepare it for a
> mainframe.  Currently I read the contents into a list as such:

> my @fields = split(/\t/, $record)
> and then I call them by $fields[0], etc.

> Would it be more beneficial to use a hash instead?  Or is that overkill?  
> I would need to set the key and then import the values from the file 
> import.

if what you're after is to improve the readability of your
script there's a few different options you have.

  * keep the array but make it more readable

it's disingenuous to write things like $fields[0], but what
if you could write $fields[ORDER_ID] - much more obvious.
you could use code like the following:

  use constant ORDER_ID => 0;
  use constant PRODUCT => 1;

  my @fields = split(/\t/, $record);

  print $fields[ORDER_ID];

conventionally the "use constant" lines would be at the top
of your script.

this is quite nice if you're concerned about the speed
impact of using hashes over arrays, as the optimizer will
replace any of these "constant values" with the respective
value at compile time, so as far as perl is concerned you've
written $fields[0]

you can read about the constant pragma with "perldoc constant".

as perl people like to chant TIMTOWTDI... so here's another
way.


  * use a hash instead of an array

this will make code which looks pretty much identical to the
last idea. ie we can say $field{order_id}. the first way you
might think of doing this might be something like:

  my @fields_array = split(/\t/, $record);
  my %fields_hash;
  $fields_hash{order_id} = $fields_array[0];
  $fields_hash{product} = $fields_array[1];

but this seems remarkably longwinded to me. i'd use "map" in
this case. map is one of the scary keywords that most people
new to perl don't understand and skip over... if there were
lots of fields and they were going to change regularly then
i might do something like:

  my $index = 0;
  my @field_names = qw( order_id product );
  my %fields_hash = map { $field_names[$index++] => $_ }
                     split(/\t/, $record);

which will put exactly the same data in %fields_hash as the
last example.


here's another way, which you might like...

  * use a different variable for each field

this does away with the hash and the array altogether...

  my ($order_id, $product) = split(/\t/, $record);

  print $order_id;

which hopefully should be self-explanatory.


there's other things that could be done, but they start to
get a bit silly. hopefully that will give you a few things
to think about.



-- 
Best Regards,
Daniel                                [EMAIL PROTECTED]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to