-
Notifications
You must be signed in to change notification settings - Fork 0
/
RDB.pm
1824 lines (1380 loc) · 38.8 KB
/
RDB.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package RDB;
use fields qw( fh col defs ncols pos comments loc mode file bindvals
bindmap bindsub nsplitcols hdrvars hdr_written );
use strict;
use vars qw( $VERSION $DEFN_RE );
$DEFN_RE = '^\s*' .
'(?:(\d+)\s+)?' .
'([\w%:@=,.][\w%:@=,.#-]*)' .
'\s+' .
'(\d*)' .
'([SsNnMm])' .
'([<=>]?)' .
'(?:\s*$|\s+(.+))' .
'$'; #'
$VERSION = '1.42';
use FileHandle;
use Carp qw( carp croak );
=head1 NAME
RDB - object methods for dealing with rdb files
=head1 SYNOPSIS
use RDB;
$rdb = new RDB;
$rdb->open( 'foo.rdb' ) || die;
$rdb = new RDB 'foo.rdb' or die;
$rdb = new RDB \*STDIN or die;
$rdb = new RDB ( 'name' => 'S', 'id' => 'N' );
$rdb->init( );
$rdb->init( 'name' => 'S', 'id' => 'N' );
$rdb->add_col( 'slap' => 'S', 'gurgle' => 'N' );
$rdb->add_col( $other_rdb );
$rdb->delete_col( 'gurgle' );
@defs = ( 'name' => 'S', 'id' => 'N' );
$rdb->init( \@defs );
$rdb->init( $other_rdb );
$rdb->rewind;
$rdb->bind( { col1 => \$col1, col2 => \$col2 } );
while ( $rdb->read( ) ) { print $col1, $cols, "\n"; }
while( $rdb->read( \%data ) ) { ... }
while( $rdb->read( \@data ) ) { ... }
while( $verbatim_line = $rdb->read_line ) { print $verbatim_line };
$rdb->write_hdr( );
$rdb->write_hdr( \*STDOUT );
$rdb->write( \%data );
$rdb->write( \@data );
$rdb->write( @data );
$rdb->set( \%attr );
$rdb->set( { AlwaysBind => 1 } );
@header_var_names = $rdb->vars;
$foo = $rdb->getvar( 'foo' );
$rdb->setvar( foo => 33 );
$hdrvars = $rdb->getvars;
print $hdrvars->{foo};
$rdb->delvar ( 'foo' );
=head1 DESCRIPTION
This module eases use of RDB data files. It creates RDB objects
which contain the necessary information for interpreting and
manipulating RDB files.
=head1 Constructor
=over 8
=item new [I<file or filehandle>, [I<mode>]]|I<\@defs>]
B<new> is the constructor, and must be called before any other methods
are invoked. It creates an B<RDB> object. It can optionally be
passed a filename to be opened and an optional mode or a reference to a glob
(which is interpreted as an already open file handle). It then
invokes the RDB::open method on the file/file handle. If a mode is
not specified, it is opened with mode C<<>. If the passed argument
is a reference to an array, RDB::init is invoked with
that argument.
=cut
sub new
{
my $this = shift;
my $class = ref($this) || $this;
my $rdb = {
fh => undef,
col => [],
defs => {},
ncols => undef,
'pos' => {},
comments => [],
hdrvars => {},
loc => undef,
mode => undef,
file => undef,
bindmap => [],
bindsub => undef,
attr => { AlwaysBind => 0 },
hdr_written => 0, # true if header has been written
nsplitcols => 0, # number of columns to pass to split;
# used only if variables are bound to
# columns
};
bless $rdb, $class;
if ( @_ )
{
if ( ! ref($_[0]) or ref($_[0]) eq 'GLOB' )
{
my ( $file, $mode ) = @_;
$rdb->open( $file, $mode ) or return undef;
}
elsif( ref( $_[0]) ne 'CODE' )
{
$rdb->init( $_[0] );
}
else
{
croak 'RDB::new called with bogus argument';
}
}
return $rdb;
}
=back
=head1 Object action methods
=over 4
=cut
=item bind( \%bindhash [, \%attrs ] )
B<bind> simplifies the processing of rdb files by allowing the
automatic assignment of values read from the rdb file to Perl
variables or arrays. Each time that the read method is called with no
arguments, it will update the variables specified in preceding calls
to C<bind>. B<bind> takes a hash of columns to be bound; the keys are
the column names, their values are references to either scalars or
arrays. In the former case, the scalar will be assigned the column's
value. In the latter case, the column's value is pushed onto the end
of the array. ( Note that the argument to bind is a hash just to
enforce the correct number of items.) For example,
$rdb->bind( { col1 => \$col1, col2 => \$col2 } );
while ( $rdb->read( ) )
{
print "$col1, $cols\n";
}
Or, using arrays,
my ( @col1, @col2 );
$rdb->bind( { col1 => \@col1, col2 => \@col2 } );
1 while ( $rdb->read( ) );
for( $i = 0 ; $i < @col1 ; $i++ )
{
print $col1[$i], ' ', $col2[$i], "\n";
}
If the same column is specified in I<succeeding> calls to B<bind>, the
new binding will override the previous binding.
However, if the same column should be bound to multiple variables, the
pC<Override> attribute may be reset using the second argument to
B<bind>:
$rdb->bind( { col1 => \$col1, col2 => \$col2 } );
$rdb->bind( { col1 => \$col1_copy }, { Override => 0 } );
The column C<col1> will now be written to both C<$col1> and C<$col1_copy>.
=cut
sub bind
{
@_ == 2 || @_ == 3 or croak 'usage: $rdb->bind( \%bindmap [, \%attrs] )';
my $rdb = shift;
my $bindmap = shift;
croak 'RDB::bind: argument not a hash'
unless ref $bindmap eq 'HASH';
my $attrs = shift;
croak 'RDB::bind: attrs not a hash'
if $attrs && ref $attrs ne 'HASH';
$attrs = { Override => 1, $attrs ? %$attrs : () };
my @bindmap = @{$rdb->{bindmap}};
# if overriding existing map, retain entries from old map which
# aren't being overridden
if ( $attrs->{Override} )
{
my @new;
while ( @bindmap )
{
my $bindval = shift @bindmap;
push @new, $bindval
unless $bindmap->{$bindval->[0]};
}
@bindmap = @new;
}
while( my ( $col, $var ) = each %$bindmap )
{
push @bindmap, [ $col, $var ];
}
$rdb->{bindmap} = \@bindmap;
$rdb->__bind_sub;
}
# optimizations here must take into account a non one-to-one mapping
# i.e., more than one variable may be bound to a column.
sub __bind_sub
{
my $rdb = shift;
my @sub;
return unless @{ $rdb->{bindmap} };
for ( my $i = 0 ; $i < @{ $rdb->{bindmap} } ; $i++ )
{
my ($col, $var) = @{ $rdb->{bindmap}[$i] };
croak( "RDB::bind: column `$col' not defined in rdb file")
unless exists $rdb->{'pos'}->{$col};
$rdb->{nsplitcols} = $rdb->{'pos'}{$col} + 2
if $rdb->{nsplitcols} < $rdb->{'pos'}{$col} + 2 ;
if ( 'SCALAR' eq ref($var) )
{
push @sub, sprintf( '${$rdb->{bindmap}[%d][1]} = $data[%d];',
$i, $rdb->{'pos'}->{$col} );
}
elsif ( 'ARRAY' eq ref($var) )
{
push @sub, sprintf( 'push @{$rdb->{bindmap}[%d][1]}, $data[%d];',
$i, $rdb->{'pos'}->{$col} );
}
else
{
croak( "RDB::bind: column `$col' -> must bind to \\\@ or \\\$" )
}
}
my $sub = join( "\n",
'use integer;',
'my $rdb = shift;',
qq{my \@data = split( "\\t", shift, $rdb->{nsplitcols});},
@sub );
$rdb->{bindsub} = $rdb->__make_sub( $sub );
croak if $@;
}
sub __make_sub
{
my ( $rdb, $statements ) = @_;
my $sub;
eval qq( \$sub = sub { $statements } );
return $sub;
}
=item close
explicitly close an rdb file. This usually need not be called, as the
file will be closed when the RDB object is destroyed.
=cut
sub close
{
1 == @_ or croak 'usage: $rdb->close()';
my ( $rdb ) = @_;
if ( $rdb->{fh} )
{
$rdb->write_hdr if _is_write( $rdb->{mode} ) && !$rdb->{hdr_written};
$rdb->{loc} = tell($rdb->{fh});
close $rdb->{fh};
$rdb->{fh} = undef;
}
}
sub _is_write
{
my $mode = shift;
return $mode =~ />/;
}
=item init( I<@defs>|I<\@defs>|I<$rdb>)
Initialize the rdb object with a set of columns. A column is
specified by both a name and a definition. Definitions technically
consist of four parts: the column name, it's type, output alignment,
and description. The latter are optional and are usually omitted.
Column types are one of C<N>, C<S>, or C<M>, for numeric, string, and
month data. Alignment is one of C<<> or C<>>.
B<init> is passed either an array (or list), an array reference, or a
reference to another B<RDB> object. In the latter case, the column
definitions of the other object are duplicated. In the former cases,
the array must contain column name and definition pairs.
The definition may take any of the following forms:
=over 8
=item *
If the definition is a scalar, it should be the column type:
$rdb->init( c1 => 'N' );
=item *
if the definition is a hash reference, it should have at least
the key C<type>, and may optionally have the keys C<width>, C<align>,
or C<desc>
$rdb->init( c1 => { type => 'N', width => 3, align => '<',
desc => 'This column is meaningless } );
=item *
if the definition is an array reference, it may have up to four
elements; the type, width, alignment, and description, in order.
The last three are optional.
$rdb->init( c1 => [ 'N', 3, '<', 'This column is meaningless' ] );
=back
Any of these forms may be mixed:
$rdb->init( c1 => 'N',
c2 => [ 'N', 32 ],
c3 => { type => 'N', desc => 'What A Nice Column' } );
=cut
sub init
{
2 <= @_ or croak 'usage: $rdb->init(@defs|\@defs)';
my $rdb = shift;
$rdb->{ncols} = 0;
$rdb->{col} = [];
$rdb->{defs} = {};
$rdb->{pos} = {};
$rdb->{comments} = [];
$rdb->{hdrvars} = {};
if ( UNIVERSAL::isa( $_[0], 'RDB' ) )
{
my $orig = $_[0];
$rdb->{comments} = [ @{$orig->{comments}} ];
$rdb->{hdrvars} = { %{$orig->{hdrvars}} };
}
eval { $rdb->_addcols(@_); };
croak "RDB::init $@" if $@;
}
=item init_tpl( $file_name | \$tpl_string )
Initialize an RDB object from an RDB header template. If the passed
argument is a scalar, it should contain the name of a file containing
the template. If it's a reference it should be a reference to a
scalar containing the template. An RDB header template is description
of the header in the following format.
Each column is specified on a separate line, and contains up to
four white space delimited fields:
=over 8
=item 1
an optional field containing the column's zero based index. If not specified,
the ordering of the field in the template is used. For example,
fee S
fie N
fo N
fum N
is equivalent to
0 fee S
1 fie N
2 fo N
3 fum N
Be careful when mixing lines with and without an index:
fee S
2 fie N
fo N
fum N
is equivalent to
0 fee S
2 fie N
2 fo N
3 fum N
which will result in an error. Indices must be unique.
There's a further degeneracy which must be avoided:
3 N S
Is that an index of C<3>, a name of C<N> and a type of C<S>, or is
that a name of C<3>, a type of C<N> and a description of C<S>?
It is parsed as the former. To get the latter interpretation,
you'll have to include an index field.
=item 2
the column name. it may appear in quotes.
=item 3
the column type. it may include the column width as a prefix
=item 4
an optional column description
=back
Comment lines may be present, and are indicated by a leading C<#> character.
For example,
# P-to-H Decenter parameters derived from XRCF HSI off-axis images
# (single shell); used pitch=0, yaw=-20 arcmin data.
#
0 fee 6S what i get paid
1 fie 10N upon you
2 fo 10N fight or no?
3 fum 9N ble
=cut
sub init_tpl
{
my $rdb = shift;
my $tpl = shift;
$rdb->{ncols} = 0;
$rdb->{col} = [];
$rdb->{defs} = {};
$rdb->{pos} = {};
$rdb->{comments} = [];
$rdb->{hdrvars} = {};
my @cols;
my $idx = 0;
unless ( 'SCALAR' eq ref $tpl )
{
my $fh = new IO::File $tpl, "r" or
croak( "unable to open $tpl\n" );
while ( <$fh> )
{
chomp;
$rdb->_parse_template( \@cols, $idx++, $_ );
}
}
else
{
$rdb->_parse_template( \@cols, $idx++, $_ ) for split( "\n", $tpl );
}
# ensure that there are no duplicate indices
my %idxs = map { ( $_->{index}, 1 ) } @cols;
croak( "duplicate index values in template\n" )
if keys %idxs != @cols ;
$rdb->_addcols( map { ( $_->{name}, $_ ) }
sort { $a->{index} <=> $b->{index} } @cols );
}
sub _parse_template
{
my ( $rdb, $cols, $idx, $tpl ) = @_;
local $_ = $tpl;
# store comments
if ( /^\s*\#/ )
{
s/^#//;
$rdb->add_comments( $_ ) ;
}
else
{
if ( $tpl =~ /$DEFN_RE/ )
{
push @$cols, {
index => defined $1 ? $1 : $idx,
name => $2,
width => $3,
type => $4,
align => $5,
desc => $6 };
}
else
{
croak( "illegal template definition `$tpl'\n");
}
}
}
=item write_tpl( $filename | $fh)
Write an RDB template for the current RDB object. The argument may be
a scalar, it which case it should contain the name of a file to which
to write the template, or a filehandle.
=cut
sub write_tpl
{
my $rdb = shift;
my $fh = shift;
unless ( ref $fh )
{
my $fh_t = new IO::File $fh, "w"
or croak( "unable to create $fh\n" );
$fh = $fh_t;
}
$rdb->_write_hdr_comments( $fh );
# turn off warnings here; don't care about undefined values, as
# they are just attributes that haven't been defined.
local $^W = 0;
# index, name, type, desc
my %max = ( name => 0, width => 0);
foreach ( @{$rdb->{col}} )
{
$max{name} = length( $_ ) if $max{name} < length( $_ );
$max{width} = length( $rdb->{defs}{$_}{width} ) if $max{width} < length( $rdb->{defs}{$_}{width} );
}
foreach ( sort { $rdb->{pos}{$a} <=> $rdb->{pos}{$b} } @{$rdb->{col}} )
{
printf $fh "%4d\t%$max{name}s\t%-$max{width}s%s%s\t%s\n",
$rdb->{pos}{$_}, $_,
$rdb->{defs}{$_}{width},
$rdb->{defs}{$_}{type},
($rdb->{defs}{$_}{align} || ' '),
$rdb->{defs}{$_}{desc};
}
}
=item add_col( I<@defs>|I<\@defs>|I<$rdb>)
Add new columns to the rdb object. See the description of the
B<init()> method for the specification of the column names and
definitions. Existing columns are not duplicated; their definitions
are changed to the passed type.
=cut
sub add_col
{
2 <= @_ or croak 'usage: $rdb->add_col(@defs|\@defs)';
my $rdb = shift;
eval { $rdb->_addcols(@_); };
croak "RDB::add_col $@" if $@;
}
sub _addcols
{
my $rdb = shift;
my @defs;
if ( 2 <= @_ )
{
@defs = @_;
@defs % 2 and die 'missing definition';
}
else
{
ref($_[0]) or die 'argument must be list or reference to array';
if ( ref $_[0] eq 'ARRAY' )
{
@defs = @{$_[0]};
}
else
{
my $src = shift;
if ( UNIVERSAL::isa( $src, 'RDB' ) )
{
push @defs, map { $_, $src->{defs}{$_} } @{$src->{col}};
}
else
{
die( "don't know what to make of argument" );
}
}
}
my @fields = qw( type width align desc );
# slurp column name, definition pairs
while( my ( $col, $def ) = splice( @defs, 0, 2 ) )
{
unless ( exists $rdb->{defs}{$col} )
{
push @{$rdb->{col}}, $col;
$rdb->{pos}{$col} = $rdb->{ncols};
$rdb->{ncols}++;
}
# it's a hash; it should have 'width', 'type', 'align', 'desc' fields
if ( 'HASH' eq ref $def )
{
$rdb->{defs}{$col}{$_} = $def->{$_} || ''
foreach @fields;
}
# it's an array; it should have 4 fields, as above
elsif ( 'ARRAY' eq ref $def )
{
my @tmp = @{$def};
$rdb->{defs}{$col}{$_} = shift @tmp || ''
foreach @fields;
}
# any other type of ref is bogus
elsif( ref $def )
{
croak( "RDB::init: illegal reference in def for `$col'" );
}
# ordinary scalar, it's the type
else
{
@{$rdb->{defs}{$col}}{@fields} = ( '', $def, '', '' );
}
}
}
=item delete_col( @cols )
delete the specified columns from the object. This is only applicable
to RDB files open for writing, and only before the RDB header has
been written out.
$rdb->delete_col( 'a', 'b' );
=cut
sub delete_col
{
@_ > 1 or croak 'RDB::delete_col( @cols )';
my $rdb = shift;
my @cols = @_;
return if ($rdb->{mode} && ! _is_write($rdb->{mode}) )
|| $rdb->{hdr_written};
foreach my $col ( @cols )
{
croak( "RDB::delete_col `$col' not defined" )
unless exists $rdb->{'pos'}->{$col};
delete $rdb->{'defs'}->{$col};
$rdb->{bindmap} = [ grep { $_->[0] ne $col } @{$rdb->{bindmap}} ];
$rdb->{col} = [ grep { $_ ne $col } @{$rdb->{col}} ];
$rdb->__bind_sub;
$rdb->{ncols}--;
}
$rdb->{'pos'} = {};
@{$rdb->{'pos'}}{@{$rdb->{'col'}}} = ( 0..$#{$rdb->{col}} );
}
=item set( \%attr )
B<set> specifies the values of various attributes for the object.
The passed reference should point to a hash which may contain
the following keys:
=over 8
=item AlwaysBind
If this is set, e.g.,
$rdb->set( { AlwaysBind => 1} )
if B<RDB::bind> has been called to set up bindings between columns and
Perl variables, the Perl variables will always be updated, regardless of which
form of B<RDB::read> is called.
=back
=cut
sub set
{
my $rdb = shift;
my $attr = shift;
croak 'usage $rdb->attr( \%attr )' unless 'HASH' eq ref $attr;
$rdb->{attr} = { %{$rdb->{attr}}, $attr ? %$attr : () };
}
=item open( I<file or filehandle> [, I<mode>] )
B<open> connects to a file (if it is passed a scalar) or to an
existing file handle (if it is passed a reference to a glob).
If mode is not specified, it is opened as read only, otherwise
that specified. Modes are the standard Perl-ish ones (see
the Perl open command). If the mode is read only or read/write, it reads
and parses the RDB header. It returns the
undefined value upon error.
=cut
sub open
{
@_ >=2 or croak 'usage : $rdb->open( $file [, $mode] )';
my ( $rdb, $file, $mode ) = @_;
$mode = '<' if ! defined $mode;
$rdb->{mode} = $mode;
my $fh = new FileHandle;
if ( ref($file) )
{
$fh->fdopen( $file, $mode ) || return undef;
}
else
{
$fh->open( $file, $mode ) || return undef;
}
$rdb->{file} = $file;
# if this is open for reading, suck in the header
if ( $mode =~ /[<+]/ )
{
$rdb->{comments} = [];
while( <$fh> )
{
last unless /^\s*\#/;
chop;
s/^\s*#//;
push @{$rdb->{comments}}, $_;
# grab header variable
if ( /^:\s*(\w+)\s*=\s*(.*)/ )
{
$rdb->{hdrvars}{$1} = $2;
}
}
return undef unless defined $_;
$rdb->{'col'} = [];
$rdb->{'defs'} = {};
$rdb->{'pos'} = {};
chop;
@{$rdb->{'col'}} = split( "\t" );
@{$rdb->{'pos'}}{@{$rdb->{'col'}}} = ( 0..$#{$rdb->{col}} );
$_ = <$fh>;
return undef unless defined $_;
chop;
# chop up definition into width, type, alignment, and description
@{$rdb->{'defs'}}{@{$rdb->{'col'}}} =
map{ /(\d+)?([nNsSmM]|-+)([<>])?(?:\s+(.*))?/;
{ width => $1,
type => $2,
align => $3,
desc => $4} } split( "\t" );
# ensure that we got valid definitions
while( my ( $col, $def ) = each ( %{$rdb->{defs}} ) )
{
croak "unrecognized definition for column `$col'"
unless defined $def->{type};
# handle old /rdb format
$def->{type} = 'S' if $def->{type} =~ /-+/;
}
$rdb->{start} = tell;
$rdb->{ncols} = @{$rdb->{'col'}};
}
$rdb->{fh} = $fh;
$rdb->{loc} = tell($rdb->{fh});
1;
}
=item read( [I<\%data>|I<\@data>] )
Read in the next line from the rdb database, storing the columns into
either a hash keyed off of the column names (if passed a reference to
the hash), an array (if passed a reference to the array), or into
scalars specified by previous calls to the C<bind> method (if C<read>
is called with no arguments). It returns the undefined value upon end
of file. It does not check to ensure that there are enough columns in
the input. For example:
$rdb->read(\%data);
print "foo = $data{foo}\n";
$rdb->read(\@data);
print "The first column has value $data[0]\n";
$rdb->bind( { foo => \$foo } );
$rdb->read();
print "Foo = $foo\n";
=cut
sub read
{
@_ >=1 or croak 'usage : $rdb->read( [\%data|\@data] )';
my $rdb = shift;
my $fh = $rdb->{fh};
return undef unless defined( $_ = <$fh> );
chomp;
$rdb->{loc} = tell($rdb->{fh});
my $data = shift;
if ( ref $data eq 'HASH' )
{
@{$data}{@{$rdb->{col}}} = split( "\t", $_, $rdb->{ncols} );
}
elsif ( ref $data eq 'ARRAY' )
{
@{$data} = split( "\t", $_, $rdb->{ncols} );
}
if ( ! defined $data || $rdb->{attr}{AlwaysBind} )
{
# use bound variables to return data
croak 'RDB::read no variables have been bound'
unless defined $rdb->{bindsub};
&{$rdb->{bindsub}}( $rdb, $_ );
}
1;
}
=item read_line
C<read_line> reads a line from the rdb file without parsing it (even
to chop off the end). It returns C<undef> upon end of file.
=cut
sub read_line
{
@_ ==1 or croak 'usage : $rdb->read_line( )';
my $rdb = shift;
my $fh = $rdb->{fh};
$_ = <$fh>;
$rdb->{loc} = tell($rdb->{fh});
return undef unless defined $_;
chomp;
return $_;
}
=item rename( \%renamehash )
B<rename> is passed a hash of columns to be renamed; the keys are
the old column names, their values are the new names. It's a hash
just to enforce the correct number of items. For example,
$rdb->rename( { oldcol => 'newcol', foocol => 'boocol' } );
=cut
#'
sub rename
{
@_ == 2 or croak 'RDB::rename( \%renamevals )';
my $rdb = shift;
my $renames = shift;
croak 'RDB::rename: argument not a hash'
unless ref $renames eq 'HASH';
while ( my ( $old, $new ) = each %$renames )
{
# ignore 'em if they're the same; saves grief later
next if $old eq $new;
croak( "RDB::rename `$old' not defined in rdb file" )
unless exists $rdb->{'pos'}->{$old};
croak( "RDB::rename '$new' already defined in rdb file" )
if exists $rdb->{'pos'}->{$new};
$rdb->{'defs'}->{$new} = $rdb->{'defs'}->{$old};
delete $rdb->{'defs'}->{$old};
$rdb->{'pos'}->{$new} = $rdb->{'pos'}->{$old};
delete $rdb->{'pos'}->{$old};
foreach ( @{$rdb->{bindmap}} )
{
$_->[0] = $new if $_->[0] = $old;
}
}
foreach ( @{$rdb->{'col'}} )
{
$_ = $renames->{$_} if exists $renames->{$_};
}
}
=item reopen
B<reopen> reopens a file that has previously been opened and closed,
positioning the filepointer to where it was before it was closed. It
retains the previous access mode. It does not reopen files passed to
the original call of rdb::open as references. It returns the
undefined value upon error.
=cut