[buug] Perl question

Brian Dessent brian at dessent.net
Thu Oct 16 03:09:22 PDT 2003


Joseph Zitt wrote:

($email,$itemcategory,$subject,$adtype,$picurl,$adindex,$descrip,$datenum)
= split(/###/,$pre);
> 
> This list appears 39 times throughout the code, and, once I change it to
> appropriate fields, I'd like to just deal with it once and refer to it
> the other times, rather than having 39 unrelated places for it to break.
> Is there a good way to do this?

Two ways come to mind, besides the obvious solution of using an array
and referencing fields by the index number (which is probably quite ugly
to maintain.)

The first would be something like:

use constant VARNAMES =>
'($email,$itemcategory,$subject,$adtype,$picurl,$adindex,$descrip,$datenum)'; 
# this line may be wrapped by email program

and then

eval VARNAMES . ' = split(/###/, $pre)';


The second (and probably better) way would be to just use an associative
array (hash):

sub parse_fields {
  my $pre = shift;
  my @fields = split(/###/, $pre);
  my $href = {};

  $href->{$_} = shift @fields foreach( qw{email itemcategory subject
adtype picurl adindex descrip datenum} );
  
  return $href;
}

and then

my $foo = parse_fields($pre);
print "email address is $foo->{email}, subject is $foo->{subject}";

Brian



More information about the buug mailing list