[mapserver-users] XBase Question--adding columns to a .dbf file

imap at chesapeake.net imap at chesapeake.net
Wed Oct 3 14:54:39 PDT 2001


On the XBase Question about adding columns...
This type of program should work OK.  You end up
having to build a new file, but that isnt a bad
thing.

 # add_column.pl
 use XBase;

 my $table = new XBase $ARGV[0] or die XBase->errstr;
 my @fn = $table->field_names();
 my @ft = $table->field_types();
 my @fl = $table->field_lengths();
 my @fd = $table->field_decimals();
 #
 # HERE you will have to push additional values into each
 # of the arrays above. (ie new Columns)
 # push @fn, "NEWCOL1","NEWCOL2";
 # push @ft, "C","C";
 # push @fl, "25","20";
 # push @fd, "undef","undef";
 #
 my $newtable = XBase->create("name" => $ARGV[1],
                   "field_names" => [@fn],
                   "field_types" => [@ft],
                   "field_lengths" => [@fl],
                   "field_decimals" => [@fd] );
 for $x (0 .. $table->last_record) {
     @rec = $table->get_record($x);
     next if ($deleted);
     #
     # push new data onto @rec or leave empty
     #
     $newtable->set_record($x, at rec);
 }


I hope that works for you... 


Regards,

Chris Stuber (mapsurfer)
Silicon Mapping Solutions, Inc.
(410)257-3187





> klehr1 at tampabay.rr.com wrote:
> 
> I'd like to add two columns to a current .dbf file using the XBase perl
> module.
> 
> Could someone provide me a small piece of code to accomplish this task.
> 
> I'm not sure of the syntax for XBase to grab a row, chop it into its fields,
> add 2 more fields to the array, repack it into the xbase format then write it
> to a new .dbf (say ARGV[1]).
> 
> i.e. in plain text file say tab delimited
> 
> if (!$ARGV[1])
> {
>   print "\n Invalid usage...Usage:  add_columns.pl CURRENTFILE NEWFILE\n";
>   exit;
> }
> open(INPUT, $ARGV[0]) || die "Could not open $ARGV[0]";
> open(OUTPUT, ">$ARGV[1]");
> 
> while(<INPUT>)
> {
>   chomp();
>   @fields = split(/\t/, $_);  # tab delimited data
>   $fields[$#fields + 1] = "new data element 1";    # add an element to the
> array
>   $fields[$#fields + 1] = "new data element 2";    # add another element
>   print "@fields\n";
>   $output_string = join "\t", @fields;
>   print OUTPUT "$output_string\n";
> }
> close(INPUT);
> close(OUTPUT);
> I'd like to do the same with .dbfs (append two columns to the current .dbf)
> 
> Thank you
> Steve Lehr



More information about the MapServer-users mailing list