lib/Kx.pm untested

filter: Statementstmt 0.0% 0 / 890 Branchbran 0.0% 0 / 374 Conditioncond 0.0% 0 / 134 Subroutinesub 0.0% 0 / 115 Podpod 0.0% 0 / 99 totaltotal 0.0% 0 / 1612 CC 188 SCAR 38.2
CC
188
Cov
0%
TIEARRAY
240.0
TIEHASH
240.0
Tnew
110.0
CRAP 45.4
1 package Kx;
2 $Kx::VERSION = '0.042';
3 use 5.008;
4 use strict;
5 use warnings;
6 use Carp;
7 use POSIX ();
8  
9 my $DEBUG = 0;
10  
11 my %NULL = (
12 'symbol' => '`',
13 'short' => "0Nh",
14 'int' => "0N",
15 'long' => "0Nj",
16 'real' => "0Ne",
17 'float' => "0n",
18 'char' => " ",
19 'month' => '0Nm',
20 'date' => '0Nd',
21 'datetime' => '0Nz',
22 'minute' => '0Nu',
23 'second' => '0Nv',
24 'time' => '0Nt',
25 );
26 my %CAST = (
27 'symbol' => '`$"',
28 'short' => '"h"$',
29 'int' => '"i"$',
30 'long' => '"j"$',
31 'real' => '"e"$',
32 'float' => '"f"$',
33 'char' => '"c"$',
34 'month' => '"m"$',
35 'date' => '"d"$',
36 'datetime' => '"z"$',
37 'minute' => '"u"$',
38 'second' => '"v"$',
39 'time' => '"t"$',
40 );
41  
42 my @TYP = qw/KC KD KE KF KG KH KI KJ KM KS KT KU KV KZ XD XT/;
43  
44 my %DB = (); # Place to store class wide connections to KDBs
45  
46 sub whowasi { ( caller(1) )[3] . '()' }
47  
48 sub AUTOLOAD {
49  
50 # This AUTOLOAD is used to 'autoload' constants from the constant()
51 # XS function.
52  
53 my $constname;
54 our $AUTOLOAD;
55 ( $constname = $AUTOLOAD ) =~ s/.*:://;
56 croak "&Kx::constant not defined" if $constname eq 'constant';
57 my ( $error, $val ) = constant($constname);
58 if ($error) { croak $error; }
59 {
60 no strict 'refs';
61 *$AUTOLOAD = sub { $val };
62 }
63 goto &$AUTOLOAD;
64 }
65  
66 require XSLoader;
67 XSLoader::load( 'Kx', $Kx::VERSION );
68  
69 =head1 NAME
70  
71 Kx - Perl extension for Kdb+ L<http://kx.com>
72  
73 =head1 SYNOPSIS
74  
75 use Kx;
76  
77 my $k = Kx->new(host=>'localhost', port=>2222);
78 $k->connect() or die "Can't connect to Kdb+ server";
79  
80 my $rtn = $k->cmd('til 8');
81 my $sum = $k->cmd('{x+y}', $k->int(5)->kval, $k->int(7)->kval);
82  
83 my $lst = $k->listof(5, Kx::KI());
84 for (0 .. 4) {
85 $lst->at($_, $_);
86 }
87 my $ktyp = Kx::kType($lst->kval);
88 my $lst_perl = $lst->val;
89  
90  
91 =head1 DESCRIPTION
92  
93 Alpha code.
94 Create a wrapper around Kdb+ and Q in Perl using the C interface to Kdb+
95  
96 =head1 EXPORT
97  
98 None by default.
99  
100 =head1 METHODS
101  
102 =cut
103  
104 =head2 New
105  
106 my $k = Kx->new(name=>'local22', host=>'localhost', port=>2222);
107  
108 Create a new Kx object. Set the connection paramaters to conect to 'host'
109 and 'port' as specified.
110  
111 No connection is made to the server until you call $k->connect()
112  
113 If you don't define a name it defaults to 'default'. Each subsequent call
114 to new() will use the same 'default' connection.
115  
116 So once you make a connection later calls to new() with the same name
117 will use the same connection without further connect() calls required.
118  
119 my $k = Kx->new(host=>'localhost', port=>2222);
120 $k->connect() or die "Can't connect to Kdb+ server";
121  
122 # picks up previous default connection to localhost port 2222 and
123 # will use it as well.
124 my $k1 = Kx->new();
125  
126 Also username and passwords are supported. Just add the userpass
127 attribute thus:
128  
129 $k = Kx->new(name=>'local22',
130 host=>'localhost',
131 port=>2222,
132 userpass=>'user:pass');
133  
134 =cut
135  
136 # we use %DB to hold all our connection details.
137 sub new {
138 my $self = shift;
139 my %opts = @_;
140 my $class = ref($self) || $self;
141  
142 my $name = 'default';
143 $name = $opts{'name'} if defined $opts{'name'};
144  
145 my $ref = { 'name' => $name };
146 if ( defined $opts{'host'} ) {
147 $DB{$name}{'host'} = $opts{'host'};
148 }
149 if ( defined $opts{'port'} ) {
150 $DB{$name}{'port'} = $opts{'port'};
151 }
152 if ( defined $opts{'userpass'} ) {
153 $DB{$name}{'userpass'} = $opts{'userpass'};
154 }
155 if ( defined $opts{'check_for_errors'} ) {
156 $DB{$name}{'check_for_errors'} = $opts{'check_for_errors'};
157 }
158  
159 # Get hold of any previously defined connection handle
160 if ( defined $DB{$name}{'kdb'} ) {
161 $ref->{'kdb'} = $DB{$name}{'kdb'}; # no need for connect
162 $DB{$name}{'count'}++;
163 }
164 return bless $ref, $class;
165 }
166  
167 =head2 Connect
168  
169 To connect to the 'default' server.
170  
171 unless($k->connect()) {
172 warn "Can't connect to Kdb+ server\n";
173 }
174  
175 To connect to a defined server say 'local22'
176  
177 unless($k->connect('local22')) {
178 warn "Can't connect to local22 Kdb+ server\n";
179 }
180
181 =cut
182  
183 sub connect {
184 my $self = shift;
185 my $name = shift || 'default';
186  
187 return undef unless exists $DB{$name}{'host'} && exists $DB{$name}{'port'};
188  
189 if ( !defined $DB{$name}{'kdb'} ) {
190  
191 # Create a new connection
192 # host, port and username password details
193 if ( defined $DB{$name}{'userpass'} ) {
194 $DB{$name}{'kdb'} = khpu(
195 $DB{$name}{'host'},
196 $DB{$name}{'port'},
197 $DB{$name}{'userpass'}
198 );
199 }
200  
201 # host, port only
202 else {
203 $DB{$name}{'kdb'} = khp( $DB{$name}{'host'}, $DB{$name}{'port'} );
204 }
205 unless ( $DB{$name}{'kdb'} > 0 ) {
206 carp "Kx->connect failed to connect. " . &whowasi . "\n" if $DEBUG;
207 undef $self->{'kdb'};
208 undef $DB{$name}{'kdb'};
209 return undef;
210 }
211 }
212  
213 # Are we moving between connections
214 if ( $self->{'name'} ne $name ) {
215 $DB{ $self->{'name'} }{'count'}--;
216 }
217  
218 $DB{$name}{'count'}++;
219 $self->{'kdb'} = $DB{$name}{'kdb'};
220 $self->{'name'} = $name;
221  
222 return $self->{'kdb'};
223 }
224  
225 =head2 Environment
226  
227 There are a number of environment details you can glean from the Kdb+
228 server you are connected to. They are:
229  
230 my $arrayref = $k->tables; # The tables defined
231 my $arrayref = $k->funcs; # The functions defined
232 my $arrayref = $k->views; # The views defined
233 my $arrayref = $k->variables; # The variables defined
234 my $arrayref = $k->memory; # The memory details \w
235  
236 my $dir = $k->cwd; # The current working directory
237 my $dir = $k->chdir($newdir); # Set the cwd
238 my $num = $k->GMToffset; # Offset from GMT for times
239  
240 If you make changes that effects these environmental details then call
241 the env() method to update what is known. This module doesn't continually
242 hassle the server for these details.
243  
244 my @details = $k->env; # Get the environment from the server
245  
246 $details[0] => [ tables ]
247 $details[1] => [ funcs ]
248 $details[2] => [ views ]
249 $details[3] => [ variables ]
250 $details[4] => 'GMToffset'
251 $details[5] => 'releasedate'
252 $details[6] => 'gmt'
253 $details[7] => 'localtime'
254 $details[8] => [ memory ]
255 $details[7] => 'cwd'
256  
257 You can also execute OS commands on the server end and gather the results
258 like this.
259  
260 $arref = $k->oscmd("ls -l /");
261  
262 =cut
263  
264 sub env {
265 my $self = shift;
266 return undef unless defined $self->{'kdb'};
267  
268 # OK we have aconnection and it is valid. Pick up some meta details
269 # from the server
270 $self->{'tables'} = k2parray0( k( $self->{'kdb'}, '\a' ) );
271 $self->{'funcs'} = k2parray0( k( $self->{'kdb'}, '\f' ) );
272 $self->{'views'} = k2parray0( k( $self->{'kdb'}, '\b' ) );
273 $self->{'variables'} = k2parray0( k( $self->{'kdb'}, '\v' ) );
274 $self->{'GMToffset'} = k2pscalar0( k( $self->{'kdb'}, '(.z.Z-.z.z)*24' ) );
275 $self->{'releasedate'} = k2pscalar0( k( $self->{'kdb'}, '.z.k' ) );
276 $self->{'gmt'} = k2pscalar0( k( $self->{'kdb'}, '.z.z' ) );
277 $self->{'local'} = k2pscalar0( k( $self->{'kdb'}, '.z.Z' ) );
278 $self->{'mem'} = k2parray0( k( $self->{'kdb'}, '\w' ) );
279 $self->{'cwd'} = k2pscalar0( k( $self->{'kdb'}, '\cd' ) );
280  
281 return (
282 $self->{'tables'}, $self->{'funcs'}, $self->{'views'},
283 $self->{'variables'}, $self->{'GMToffset'}, $self->{'releasedate'},
284 $self->{'gmt'}, $self->{'local'}, $self->{'mem'},
285 $self->{'cwd'},
286 );
287 }
288  
289 # a:@[.:;"\\ls -l /tmp/zzz > /tmp/.qoscmd 2>&1; cat /tmp/.qoscmd";()]
290 sub oscmd {
291 my $self = shift;
292 my $cmd = shift || return undef;
293 my $cap = shift;
294  
295 my $q = '@[.:;"\\\\' . $cmd;
296  
297 if ( defined $cap ) {
298  
299 # Use cap as a capture file to grap stdout and stderr
300 $q .= "> $cap 2>&1; cat $cap";
301 }
302  
303 $q .= '";()]';
304 my $ref = k2parray0( k( $self->{'kdb'}, $q ) );
305 my @d = map { $_->[0] } @$ref;
306 return \@d;
307 }
308  
309 sub memory {
310 my $self = shift;
311 $self->{'mem'} = k2parray0( k( $self->{'kdb'}, '\w' ) );
312 return $self->{'mem'};
313 }
314  
315 sub cwd {
316 my $self = shift;
317 $self->{'cwd'} = k2pscalar0( k( $self->{'kdb'}, '\cd' ) );
318 return $self->{'cwd'};
319 }
320  
321 sub chdir {
322 my $self = shift;
323 my $d = shift || '';
324 $self->{'cwd'} = k2pscalar0( k( $self->{'kdb'}, "\\cd $d" ) );
325 $self->{'cwd'} = k2pscalar0( k( $self->{'kdb'}, '\cd' ) );
326 return $self->{'cwd'};
327 }
328  
329 sub tables {
330 my $self = shift;
331 $self->env unless defined $self->{'tables'};
332 return undef unless $self->{'tables'};
333 return $self->{'tables'};
334 }
335  
336 sub funcs {
337 my $self = shift;
338 $self->env unless defined $self->{'funcs'};
339 return undef unless $self->{'funcs'};
340 return $self->{'funcs'};
341 }
342  
343 sub views {
344 my $self = shift;
345 $self->env unless defined $self->{'views'};
346 return undef unless $self->{'views'};
347 return $self->{'views'};
348 }
349  
350 sub variables {
351 my $self = shift;
352 $self->env unless defined $self->{'variables'};
353 return undef unless $self->{'variables'};
354 return $self->{'variables'};
355 }
356  
357 sub GMToffset {
358 my $self = shift;
359 $self->env unless defined $self->{'GMToffset'};
360 return undef unless $self->{'GMToffset'};
361 return $self->{'GMToffset'};
362 }
363  
364 =head2 TABLES
365  
366 You don't need to use this just use the cmd() interface if you like.
367 However if your lazy like me.... read on
368  
369 Each of these accessors have a method name starting with 'T'. To help
370 distinguish them as cooperating methods.
371  
372 Create a new table in Kdb+ named mytab with 3 columns col1, col2 and
373 col3. The keys will be on col1 and col3 This equates to the Q command
374  
375 # Q command
376 q)mytab:([col1:;col3:] col2:)
377  
378 # The long winded Perl way
379 $k->Tnew(name=>'mytab',keys=>['col1','col3'],cols=>['col2']);
380  
381 To add data use Tinsert(). Each row is added in the order defined
382 above. This line adds 1 into col1, 2 into col3 and 3 into col2 as the
383 keys are always defined before the other columns.
384  
385 $k->Tinsert('mytab',1,2,3);
386  
387 To do a select over a table use Tselect(). Tselect() takes a variable
388 name as its first argument. The select will be executed and assigned to
389 the variable you define. This way no data is passed from Kdb+ to the
390 client until it is needed.
391  
392 $k->Tselect('a','select from mytab where col1>4');
393  
394 This is really just the same as
395  
396 # q command
397 a:select from mytab where col1>4
398  
399 To get the details of the stored selection
400  
401 my $numrows = $k->Tnumrows('a');
402 my $numcols = $k->Tnumcols('a');
403  
404 This only works on variables that are tables returned from a selection.
405  
406 Tget() Tindex() Tcol() and Theader() are only useful once you have done a
407 Tget().
408  
409 Remember it is probably better to only pull back small tables less than
410 say a few tens of thousand of rows as you'll eat up memory fast.
411  
412 You may have run a number of Tselects() and now wish to pull back the
413 data. To do this use Tget()
414  
415 $k->Tget('table'); # table must be a table in the server
416  
417 Tget() can also be used with select type queries that return a table as
418 their result. It also handles indexed tables better than the cmd()
419 method.
420  
421 To get access to random values in the returned table from Tget().
422  
423 $val = $k->Tindex(row,col);
424  
425 This only works for simple tables holding scalars in each row. Don't try
426 this if the index would point to a mulit-valued list. Actually it sort of
427 works for lists and when it does $val is an array reference. If you have
428 troubles use Tcol().
429  
430 To get the list of column names as Kdb+ knows them.
431  
432 my $header = $k->Theader();
433 print "@$header\n";
434  
435 To get the meta data for a table as defined in KDB do this.
436  
437 my @meta = $k->Tmeta($table);
438 foreach(@meta)
439 {
440 print "(name type) => (@$_)\n";
441 }
442  
443  
444 To get a Perl reference to a column of data from the table (as K is
445 column oriented) do the following:
446  
447 my $colref = $k->Tcol(0); # get the zeroth column
448 print "Column 0 data is: @$colref\n";
449  
450 I advise against using this on large columns or tables as it is very
451 memory inefficent. Better to use $k->cmd() interface to pull back
452 exactly what you want first. The column reference above is a Perl copy of
453 the data structure held in Kdb+ memory format in the client. This can be
454 over 3 times larger in core than the Kdb+ data.
455  
456 If you need to access data via rows then use $k->Trow(). Given a row
457 number it will return a reference to the row. The first row is at zero 0.
458  
459 my $row = $k->Trow(0); # get the zeroth row
460 print "Row 0 data is: @$row\n";
461  
462 Finally to delete or remove a table by name from the server:
463  
464 $k->Tdelete('table');
465  
466 Here is a list of the complete table methods we have so far:
467  
468 $k->Tnew(name=>'thename',keys=>[],cols=>[]);
469 $k->Tinsert('table',1,2,3);
470 $k->Tbulkinsert('table',col1=>[],col2=>[],...);
471 $k->Tget('select statement');
472 $scalar = $k->Tindex($row,$col);
473 $arref = $k->Tcol(2); # 3rd col vector
474 $arref = $k->Trow(2); # 3rd row
475 $arref = $k->Theader;
476 $x = $k->Tnumrows;
477 $y = $k->Tnumcols;
478 $k->Tselect('table','select statement');
479 $k->Tsave('table','file');
480 $k->Tappend('table','file');
481 $k->Tload('table','file');
482 $k->Tdelete('table');
483  
484 If you want a faster bulk insert function use:
485  
486  
487 $k->Tfastbulkinsert('mytab',$col1,$col2,$col3...);
488  
489 Here col1 col2 etc are infact in core Kdb+ structures and must be in the
490 same order as the declaration use when you used Tnew(). This is almost 3
491 times faster than Tbulkinsert but uses more memory in the client. See the
492 test files that came with this module for more details on how it is used.
493  
494 =cut
495  
496 sub Tnew {
497 my $self = shift;
498 my %arg = @_;
499  
500 return undef unless defined $self->{'kdb'};
501 return undef unless defined $arg{'name'};
502 return undef unless defined $arg{'cols'};
503  
504 delete $self->{'COLS'} if defined $self->{'COLS'};
505  
506 # string to create the table
507 my $q = $arg{'name'} . ":([";
508  
509 # string to create a bulk insert function
510 my $b = 'pblkinsert_' . $arg{'name'} . ':{insert[`' . $arg{'name'} . '](';
511  
512 my $i = 0;
513 if ( defined $arg{'keys'} ) {
514 foreach my $key ( @{ $arg{'keys'} } ) {
515 $q .= $key . ':();';
516 $b .= $key . ":(x[$i]);";
517 $i++;
518 }
519 chop($q); # one ; too many
520 }
521 $q .= "]";
522 foreach my $c ( @{ $arg{'cols'} } ) {
523 $q .= $c . ':();';
524 $b .= $c . ":(x[$i]);";
525 $i++;
526 }
527 chop($q);
528 chop($b);
529 $q .= ')'; # mytab:([col1:();col3:()]col2:())
530 $b .= ')}'; # pblkinsert_mytab:{insert[`mytab](c1:(x[0]);c2:(x[1]))}
531  
532 # Create the table
533 my $k = k( $self->{'kdb'}, $q );
534 if ( $k == 0 ) {
535 dor0($k); # release memory
536 return undef;
537 }
538 if ( kType($k) < 0 ) {
539 carp "Kx->tablecreate error ", k2pscalar($k), "\n";
540 dor0($k); # release memory
541 return undef;
542 }
543 dor0($k); # release memory
544  
545 # Create the bulkinsert function
546 $k = k( $self->{'kdb'}, $b );
547 if ( $k == 0 ) {
548 dor0($k); # release memory
549 return undef;
550 }
551 if ( kType($k) < 0 ) {
552 carp "Kx->tablecreate bulkinsert function error ", k2pscalar($k), "\n";
553 dor0($k); # release memory
554 return undef;
555 }
556  
557 dor0($k); # release memory
558 return 1;
559 }
560  
561 sub Tdelete {
562 my $self = shift;
563 my $var = shift || return undef;
564  
565 delete $self->{'COLS'} if defined $self->{'COLS'};
566  
567 #$self->{'K'} = k($self->{'kdb'},"$var: null");
568 # .[`.;();_;`d] will remove the d symbol from the current workspace
569 # This uses the Dot Fucntional form of Amend .[d;i;f;y] where
570 # d is a dictionary, `d do it in place
571 # i is and index, possibly multi level
572 # f is a function to apply
573 # y is the right hand side of a dyadic function
574 #
575 # So `. is the symbol name for the current workplace to be Ammeded in
576 # place
577 # () is an index for the whole domain of .
578 # _ is the drop function
579 # `d is the symbol name we wish to drop
580 my $k = k( $self->{'kdb'}, ".[`.;();_;`$var]" );
581 dor0($k); # release memory
582 return 1;
583 }
584  
585 sub check_for_errors {
586 my $k = shift;
587 my $q = shift || "";
588  
589 if ( $k == 0 ) {
590 carp "Undefined K structure\n";
591 return 0;
592 }
593 if ( kType($k) == -128 ) {
594 carp "K error ", k2pscalar($k), " $q\n";
595 return 0;
596 }
597 return 1;
598 }
599  
600 # $k->Tinsert('mytab',1,2,3); a single row
601 #
602 sub Tinsert {
603 my $self = shift;
604 my $table = shift;
605  
606 return undef unless defined $self->{'kdb'};
607  
608 delete $self->{'COLS'} if defined $self->{'COLS'};
609  
610 # q)insert[`mytab](1;2;3)
611 my $q = 'insert[`' . $table . '](' . join( ';', @_ ) . ')';
612  
613 my $k = k( $self->{'kdb'}, $q );
614 my $r = 1;
615 if ( exists $self->{'check_for_errors'} ) {
616 $r = check_for_errors( $k, $q );
617 }
618 dor0($k);
619 return $r;
620 }
621  
622 # $k->bulkinsert('mytab',$col1,$col2,$col3...);
623 #
624 sub bulkinsert {
625 my $self = shift;
626 my $table = shift;
627  
628 return undef unless defined $self->{'kdb'};
629  
630 # Create the argument list
631 my $cols = ktn( 0, scalar @_ );
632 for ( my $i = 0 ; $i < @_ ; $i++ ) {
633 setKarraymixed( $cols, $i, $_[$i] ) || croak "Can't setKarraymixed ";
634 }
635  
636 k1( -( $self->{'kdb'} ), "pblkinsert_$table", $cols );
637 return 1;
638 }
639  
640 # $k->Tbulkinsert('mytab',$k=>$colref,$k1=>$col1ref);
641 #
642 sub Tbulkinsert {
643 my $self = shift;
644 my $table = shift;
645  
646 return undef unless defined $self->{'kdb'};
647  
648 # q)insert[`mytab](id:($id);p:($prop);v:($v);tm:($z))
649 my $q = 'insert[`' . $table . '](';
650 while (@_) {
651 my $key = shift @_;
652 my $aref = shift @_;
653 return undef unless $aref;
654 $q .= "$key:(" . join( ';', @$aref ) . ');';
655 }
656 chop $q;
657 $q .= ')';
658  
659 k( -( $self->{'kdb'} ), $q );
660 return 1;
661 }
662  
663 sub Tsave {
664 my $self = shift;
665 my $table = shift;
666 my $file = shift;
667  
668 return undef unless defined $table;
669 if ( !defined $file && defined $table ) {
670  
671 # Then filename os tablename
672 $file = $table;
673 }
674  
675 return undef unless defined $self->{'kdb'};
676  
677 # q).[`:filename;();:;tablename]
678 my $q = '.[`$":' . $file . '";();:;' . $table . ']';
679  
680 my $k = k( $self->{'kdb'}, $q );
681 my $r = check_for_errors( $k, $q );
682 dor0($k);
683 return $r;
684 }
685  
686 sub Tappend {
687 my $self = shift;
688 my $table = shift;
689 my $file = shift;
690  
691 return undef unless defined $table;
692 if ( !defined $file && defined $table ) {
693  
694 # Then filename os tablename
695 $file = $table;
696 }
697  
698 return undef unless defined $self->{'kdb'};
699  
700 # q).[`:filename;();:;tablename]
701 my $q = '.[`$":' . $file . '";();,;' . $table . ']';
702  
703 my $k = k( $self->{'kdb'}, $q );
704 my $r = check_for_errors( $k, $q );
705 dor0($k);
706 return $r;
707 }
708  
709 sub Tload {
710 my $self = shift;
711 my $table = shift;
712 my $file = shift;
713  
714 return undef unless defined $table;
715 if ( !defined $file && defined $table ) {
716  
717 # Then filename os tablename
718 $file = $table;
719 }
720  
721 return undef unless defined $self->{'kdb'};
722  
723 # q).[`:filename;();:;tablename]
724 my $q = "$table: value`\$\":$file\"";
725  
726 my $k = k( $self->{'kdb'}, $q );
727 my $r = check_for_errors( $k, $q );
728 dor0($k);
729 return $r;
730 }
731  
732 # $k->Tselect('a','select sum size by sym from trade where date=2006.09.25');
733 #
734 #To get the details of the stored selection
735 #
736 # my $numrows = $k->Tnumrows('a');
737 # my $numcols = $k->Tnumcols('a');
738 sub Tselect {
739 my $self = shift;
740 my $table = shift || croak;
741  
742 return undef unless defined $self->{'kdb'};
743  
744 # q)a: select col1 from mytab where col1 > 7
745 my $q = $table . ':' . join( '', @_ );
746  
747 my $k = k( $self->{'kdb'}, $q );
748 my $r = check_for_errors( $k, $q );
749 dor0($k);
750 return $r;
751 }
752  
753 sub Tnumrows {
754 my $self = shift;
755 my $table = shift || croak;
756  
757 return undef unless defined $self->{'kdb'};
758  
759 # q)count mytab
760 my $q = "count $table";
761  
762 my $k = k( $self->{'kdb'}, $q );
763 my $rows = k2pscalar0($k);
764  
765 return $rows;
766 }
767  
768 sub Tnumcols {
769 my $self = shift;
770 my $table = shift || croak;
771  
772 return undef unless defined $self->{'kdb'};
773  
774 my $q = "cols $table";
775  
776 my $k = k( $self->{'kdb'}, $q );
777 my $cols = k2parray0($k);
778 my $numcols = scalar @$cols;
779  
780 return $numcols;
781 }
782  
783 sub Tget {
784 my $self = shift;
785 my $cmd = shift || return undef;
786  
787 dor0( $self->{'K'} ) if defined $self->{'K'}; # release memory
788 return undef unless defined $self->{'kdb'};
789  
790 $self->{'K'} = kTable( $self->{'kdb'}, $cmd );
791 if ( $self->{'K'} == 0 ) {
792 return undef;
793 }
794 if ( kType( $self->{'K'} ) < 0 ) {
795 carp "Kx->Tget error $cmd", k2pscalar0( $self->{'K'} ), "\n";
796 return undef;
797 }
798  
799 $self->{'colnames'} = k2parray( kTableH( $self->{'K'} ) );
800 $self->{'NUMROWS'} = kTableNumRows( $self->{'K'} );
801 $self->{'NUMCOLS'} = kTableNumCols( $self->{'K'} );
802 $self->{'COLS'} = kTableCols( $self->{'K'} );
803  
804 return ( $self->{'NUMROWS'}, $self->{'NUMCOLS'} );
805 }
806  
807 sub Tmeta {
808 my $self = shift;
809 my $table = shift;
810  
811 #my $q = "select c,t from meta $table";
812 my $q = "meta $table";
813 my $meta = kTable( $self->{'kdb'}, $q );
814 return undef if $meta == 0;
815 if ( kType($meta) < 0 ) {
816 carp "Kx->meta error $q", k2pscalar0($meta), "\n";
817 return undef;
818 }
819  
820 my $rows = kTableNumRows($meta);
821 my @m = ();
822 for ( my $i = 0 ; $i < $rows ; $i++ ) {
823 my $type = kTableIndex( $meta, $i, 1 ); # Version 2.2 support
824 if ( $type =~ /^\d+/ ) {
825 $type = chr($type);
826 }
827 push( @m, [ kTableIndex( $meta, $i, 0 ), $type ] );
828 }
829 dor0($meta);
830  
831 return @m;
832 }
833  
834 sub Tcol {
835 my $self = shift;
836 my $col = shift;
837 return undef unless defined $self->{'COLS'};
838 return undef unless $col >= 0 && $col < $self->{'NUMCOLS'};
839  
840 my $c = kStructi( $self->{'COLS'}, $col );
841 return k2parray($c);
842 }
843  
844 sub Tindex {
845 my $self = shift;
846 my $row = shift;
847 my $column = shift;
848  
849 return undef unless defined $self->{'K'};
850 return undef unless defined $self->{'COLS'};
851 return undef unless $column >= 0 && $column < $self->{'NUMCOLS'};
852 return undef unless $row >= 0 && $row < $self->{'NUMROWS'};
853  
854 return kTableIndex( $self->{'K'}, $row, $column );
855 }
856  
857 sub Trow {
858 my $self = shift;
859 my $row = shift;
860  
861 return undef unless defined $self->{'K'};
862 return undef unless defined $self->{'COLS'};
863 return undef unless $row >= 0 && $row < $self->{'NUMROWS'};
864  
865 my @rtn = ();
866 my $colidx = $self->{'NUMCOLS'} - 1;
867 for my $col ( 0 .. $colidx ) {
868 push( @rtn, kTableIndex( $self->{'K'}, $row, $col ) );
869 }
870  
871 return \@rtn;
872 }
873  
874 sub Theader {
875 my $self = shift;
876 return undef unless defined $self->{'K'};
877 return undef unless defined $self->{'COLS'};
878  
879 return k2parray( kTableH( $self->{'K'} ) );
880 }
881  
882 =head2 COMMANDS
883  
884 Execute the code on an already accessable Kdb+ server. The query
885 is executed and the results are held in K structures in RAM. Example
886  
887 $return = $k->cmd('b:til 100');
888  
889 If you just what to send a command to the Kdb+ server and not wait then
890 use the following. No return value is provided.
891  
892 $k->whenever('b:til 100');
893  
894 The cmd() method also allows up to two extra arguments that are normally
895 K objects. You normally call cmd() this way when you have a function to
896 call. Here is a dodgy example.
897  
898 my $data = $k->listof(length($arrsym), Kx::KG()); # list of bytes
899 $data->setbin($arrsym);
900  
901 $result = $k->cmd('{[x]insert[`mytab](0;x;.z.z)}', $data->kval);
902  
903 The cmd() function will return a reference to an array if the Q command
904 returns a list. It will return a simple scalar if the result is a scalar
905 response from Q. It will return a hash reference if the return result
906 from Q is either table/keyed table/dictionary. You need to know what you
907 are doing so can know what the result is (or use Perl's ref()).
908  
909 Do not execute queries that return large 'keyed' tables as a copy of the table
910 in unkeyed form is held to convert to a Perl Hash before being freed.
911  
912 Note: cmd() does not convert a keyed table to an unkeyed table in memory.
913 It holds onto what was passed back from KDB+ as is. If you want get at
914 the underlying K structure and change it use Tget() instead. Tget() will
915 convert a keyed table to an unkeyed table and hold it in memory.
916  
917 If you have a Q script that you wish to run against the Kdb+ server you
918 can use the do(file) method. Any error in your script that is caught will
919 stop do(file) from proceeding. If you don't care when it is done then use
920 dolater(file).
921  
922 Both do() and dolater() don't return anything useful. They just blindly
923 execute each line of Q against the server. If you want to check each
924 command and do stuff as a result then use cmd() and check the result.
925  
926 An example file name foo.txt holds the lines:
927  
928 t:([]a:();b:())
929 insert[`t](`a;10.70)
930 insert[`t](`b;-5.6)
931 insert[`t](`c;21.73)
932  
933 You can run that file by doing this:
934  
935 $k->do("foo.txt");
936  
937 =cut
938  
939 sub do {
940 my $self = shift;
941 my $file = shift || return undef;
942  
943 my $k;
944 open( F, $file ) || return undef;
945 while (<F>) {
946 chomp;
947 $k = k( $self->{'kdb'}, $_ );
948 if ( $k == 0 ) {
949 dor0($k); # release memory
950 return undef;
951 }
952 if ( kType($k) == -128 ) {
953 my $err = k2pscalar0($k);
954 carp "Kx->do error $file $err on line $_\n";
955 return $err;
956 }
957 dor0($k); # release memory
958 }
959 return 1;
960 }
961  
962 sub cmd {
963 my $self = shift;
964 my $cmd = shift || return undef;
965 my @arg = @_;
966  
967 my $k;
968 if ( @arg > 2 ) {
969 carp "Kx->cmd(self,cmd,arg1,arg2) max extra args is 2, use lists";
970 return undef;
971 }
972 return undef unless defined $self->{'kdb'};
973  
974 if ( @arg == 1 ) {
975 $k = k1( $self->{'kdb'}, $cmd, $arg[0] );
976 }
977 elsif ( @arg == 2 ) {
978 $k = k2( $self->{'kdb'}, $cmd, $arg[0], $arg[1] );
979 }
980 else {
981 $k = k( $self->{'kdb'}, $cmd );
982 }
983  
984 if ( $k == 0 ) {
985 return undef;
986 }
987  
988 dor0( $self->{'K'} ) if defined $self->{'K'}; # release memory
989 $self->{'K'} = $k;
990 _val($k);
991 }
992  
993 sub whenever {
994 my $self = shift;
995 my $cmd = shift || return undef;
996  
997 return undef unless defined $self->{'kdb'};
998  
999 k( -( $self->{'kdb'} ), $cmd );
1000 return undef;
1001 }
1002  
1003 =head2 ATOMS and STRUCTURES
1004  
1005 To create Kdb+ atoms locally in RAM use the following calls.
1006  
1007 my $d;
1008 $d=$k->bool(0); # boolean
1009 $d=$k->byte(100); # char
1010 $d=$k->char(ord('a')); # char
1011 $d=$k->short(20);
1012 $d=$k->int(70);
1013 $d=$k->long(93939);
1014 $d=$k->real(20.44); # remember 20.44 may look close as a real
1015 $d=$k->float(20.44); # should look closer to 20.44 as a float
1016 $d=$k->sym('mysymbol'); # A Kdb+ symbol
1017 $d=$k->date(2007,4,22); # integer encoded date year, month, day
1018 $d=$k->dt(time()); # Kdb+ datetime from Unix epoch
1019 $d=$k->tm(100); # Time type in milliseconds
1020  
1021 These allow for fine grained control over the 'type' of K object you
1022 want. If you don't mind particularly about the type conversions then you
1023 can use perl2K() like this.
1024  
1025 $d = $k->perl2K('mysymbol');
1026 $d = $k->perl2K([qw/this will be a K list of symbols/]);
1027 $d = $k->perl2K({this => 1, that => 2, 'is a' => 'dict'});
1028  
1029 To get a Perl value back from a Kdb+ atom try this;
1030  
1031 my $val = $d->val();
1032  
1033 To get the internal value back from a Kdb+ atom try this;
1034  
1035 my $kval = $k->kval; # used in $x->cmd('func', $kval)
1036  
1037 As a further comment on the date() method. When you look at the value
1038 retuned from a date() call it is in epoch seconds.
1039  
1040 my $date = $k->date(2007,4,22);
1041 print scalar localtime($date->val),"\n";
1042  
1043 Further more, KDB+ Datetimes are held as a C double in memory. The
1044 integral part is the number of days since 1/1/2000 and the fractional
1045 part is the fraction of the day. You have some control over how datetimes
1046 are returned from KDB+ back into Perl data structures. By default a
1047 conversion to Unix epoch seconds will be made. You can also get epoch seconds
1048 with milliseconds and you can also turn off conversion all together.
1049  
1050 Kx::__Z2epoch(0); # turn off Kdb+ to Unix epoch conversion
1051 Kx::__Z2epoch(1); # turn on Kdb+ to Unix epoch conversion (default)
1052 Kx::__Z2epoch(2); # turn on Kdb+ to Unix epoch conversion plus millisecs
1053  
1054 These have immediate effects on how datetimes are converted into Perl
1055 data structures. These do not effect what is held in RAM after a call to
1056 KDB+ has been made, just how they are converted into Perl.
1057  
1058 These methods use the underlying functions as listed below. Don't use
1059 these unless you know what your doing. They are listed here for
1060 completeness and so you can use them if you really want. But don't.
1061  
1062 Kx::kb(integer) => Create boolean 0|1
1063 Kx::kg(integer) => Create a byte/char
1064 Kx::kh(integer) => Create a short
1065 Kx::ki(integer) => Create and integer
1066 Kx::kj(longval) => Create a long
1067 Kx::ke(realval) => Create a real
1068 Kx::kf(floatval) => Create a float
1069 Kx::kc(charval) => Create a char from an int ord()
1070 Kx::ks(symbol) => Create a symbol from a string
1071 Kx::kd(date) => Create a date - See K dates
1072 Kx::kz(datetime) => Create a datetime - See K dates
1073 Kx::kt(time) => Create a time
1074  
1075 Kx::p2k($ref) => return a K structure describing the Reference
1076 Kx::k2p(K) => return a Perl structure from a Kdb+ structure
1077  
1078 Kx::k2pscalar(K) => return a scalar from a Kdb+ atom
1079 Kx::k2parray(K) => return an array from a Kdb+ list
1080 Kx::k2phash(K) => return a hash from a Kdb+ dict/table
1081  
1082 Kx::phash2k($href) => return a Kdb+ dict from a Perl hash ref
1083 Kx::parray2k($aref) => return a Kdb+ list from a Perl array ref
1084 Kx::pscalar2k($srf) => return a Kdb+ atom from a Perl scalar ref
1085  
1086 Example:
1087  
1088 # Simple create
1089 my $bool = $k->bool(0);
1090 print "My boolean in K is ",$bool->val,"\n";
1091  
1092 =cut
1093  
1094 # Create an atom in a generic fashion not an OO function call. Creates a
1095 # K object as its return value
1096 sub _atom {
1097 my ( $val, $code ) = @_;
1098  
1099 # Check for null
1100 return (undef) unless ( defined $val );
1101  
1102 # Default to creating symbols
1103 $code = \&ks unless defined $code;
1104  
1105 my $k = Kx->new();
1106 $k->{'K'} = $code->($val);
1107 return $k;
1108 }
1109  
1110 # There is very little checking done by this code.
1111 sub bool { _atom( $_[1], \&kb ); }
1112 sub byte { _atom( $_[1], \&kg ); }
1113 sub short { _atom( $_[1], \&kh ); }
1114 sub int { _atom( $_[1], \&ki ); }
1115 sub long { _atom( $_[1], \&kj ); }
1116 sub real { _atom( $_[1], \&ke ); }
1117 sub float { _atom( $_[1], \&kf ); }
1118 sub char { _atom( $_[1], \&kc ); }
1119 sub sym { _atom( $_[1], \&ks ); }
1120 sub date { _atom( ymd( $_[1], $_[2], $_[3] ), \&kd ); }
1121 sub month { _atom( $_[1], \&ki ); }
1122 sub second { _atom( $_[1], \&ki ); }
1123 sub dt { _atom( epoch2Z( $_[1] ), \&kz ); }
1124 sub tm { _atom( $_[1], \&kt ); }
1125  
1126 sub perl2k {
1127 my $self = shift;
1128 my $v = shift || return undef;
1129  
1130 my $k = Kx->new();
1131 if ( ref($v) ) {
1132 if ( ref($v) eq 'SCALAR' || ref($v) eq 'ARRAY' || ref($v) eq 'HASH' ) {
1133 $k->{'K'} = p2k($v);
1134 }
1135 else {
1136 carp("Kx->perl2k(x): x can only be a ref to scalar, array, hash");
1137 }
1138 }
1139 else {
1140 $k->{'K'} = p2k( \$v );
1141 }
1142 return $k;
1143 }
1144  
1145 sub val {
1146 my $self = shift;
1147 return _val( $self->{'K'} );
1148 }
1149  
1150 sub _val {
1151 my $k = shift;
1152  
1153 return undef unless defined $k;
1154  
1155 my $type = kType($k);
1156 if ( $type == -128 ) # Its an error
1157 {
1158 my $err = k2pscalar0($k);
1159 carp "K error: $err \n";
1160 return $err;
1161 }
1162 elsif ( $type >= 0 && $type < KT() ) # Its a list
1163 {
1164 my $ref = k2parray($k);
1165  
1166 # Now if its a list of char vals or a list of bytes then we
1167 # convert it to a single string, possibly binary
1168 if ( $type == KG() || $type == KC() ) {
1169 return $ref->[0];
1170 }
1171 else # default return array ref
1172 {
1173 return $ref;
1174 }
1175 }
1176 elsif ( $type < 0 || $type == 98 || $type == 99 ) # Scalar/Hash etc
1177 {
1178 return k2p($k);
1179 }
1180 else # nothing to return so say OK
1181 {
1182 return 1;
1183 }
1184 }
1185  
1186 sub kval {
1187 return undef unless defined $_[0]->{'K'};
1188 return $_[0]->{'K'};
1189 }
1190  
1191 =head2 LISTS
1192  
1193 =head3 Simple Lists
1194  
1195 These list functions create in memory local lists outside of any 'q'
1196 running process. These will allow you to create very large simple lists
1197 without blowing out all your memory.
1198  
1199 To create a simple Kdb+ list of a single type use the listof() function.
1200 The type of the list is passed in as the second aregument and can be one
1201 of:
1202  
1203 Kx::KC() char
1204 Kx::KD() date yyyy mm dd
1205 Kx::KE() real
1206 Kx::KF() float
1207 Kx::KG() byte
1208 Kx::KH() short
1209 Kx::KI() integer
1210 Kx::KJ() long
1211 Kx::KM() month
1212 Kx::KS() symbol (internalised string)
1213 Kx::KT() time
1214 Kx::KU() minute
1215 Kx::KV() second
1216 Kx::KZ() datetime epoch seconds
1217  
1218 Example simple lists:
1219  
1220 my $list = $k->listof(20,Kx::KS()); # List of 20 symbols
1221 for( my $i=0; $i < 20; $i++)
1222 {
1223 $list->at($i,"symbol$i");
1224 }
1225  
1226 # To get at the 4th element
1227 my $sym = $list->at(3); # symbol3
1228  
1229 my $perl_list = $list->list;
1230 print "Symbols are @$perl_list\n";
1231  
1232 # dates
1233 $d = $k->listof(20,Kx::KD());
1234 for( my $i=0; $i < 20; $i++)
1235 {
1236 $d->at($i,2007,4,$i+1); # 20070401 -> 20070421
1237 }
1238  
1239 # Add an extra date to the end of the list
1240 my $day = $k->date(2007,4,30);
1241 $d->joinatom($day->kval);
1242  
1243 There is also another method defined setbin() that sets binary
1244 data into a list of bytes. You can use this to save serialised Perl
1245 data structures into Kdb+ tables (much like a blob or text field in SQL
1246 DBs). Here is an example:
1247  
1248 use Kx;
1249 use Compress::Zlib qw/compress uncompress/;
1250 use Data::Dumper;
1251 $Data::Dumper::Indent = 0; # no newlines, important
1252
1253 my $k = Kx->new(host=>"localhost", port=>2222, check_for_errors=>1);
1254 $k->connect() or die "Can't connect to Kdb+ server";
1255
1256 # create new table in q
1257 $k->Tnew(name=>'mytab',cols=>[qw/id data ts/]);
1258
1259 # Build a large complicated Perl structure.
1260 my $arr = { a=>['a','b','c',1,2,3], b=>'this is a test'};
1261 for (0..10000) {
1262 $arr->{$_} = {$_ => $_};
1263 $arr->{"a$_"} = [$_, $_];
1264 }
1265
1266 # Serialise it as a compressed piece of data
1267 my $arrsym = Dumper($arr);
1268 print "Dumper size is: ", length $arrsym, "\n";
1269 $arrsym = compress( $arrsym );
1270 print "Compress Dumper size is: ", length $arrsym, "\n";
1271
1272 # An in memory Kdb+ list of bytes to hold the compressed data
1273 my $data = $k->listof(length($arrsym),Kx::KG()); # list of length bytes
1274 $data->setbin($arrsym);
1275
1276 # Insert it into a table using a function call.
1277 $k->cmd('{[x]insert[`mytab](0;x;.z.z)}',$data->kval);
1278
1279 # Select a single row from the table, and return it's data
1280 $binary = $k->cmd('(select data from mytab where id=0)[0;`data]');
1281
1282 # Get the data back into Perl string form
1283 $arrsym = uncompress($binary);
1284 #print $arrsym,"\n";
1285
1286 # Eval the string into a Perl data structure the hard way
1287 my $VAR1;
1288 eval $arrsym;
1289 print $VAR1->{'b'},"\n";
1290  
1291 =head3 Mixed Lists
1292  
1293 # The zero in line below says its to be a mixed list
1294 my $list = $k->listof(40,0); # mixed list 40 elements
1295 $list->at(0,$k->float(22.22));
1296  
1297 $list->at(1,$k->sym('this is a test'));
1298 .
1299 .
1300 $list->at(39,$k->date(2007,2,28));
1301  
1302 This is handy for creating multiple arguments to a KDB+ function call.
1303  
1304 =cut
1305  
1306 sub joinatom {
1307 my $self = shift;
1308 my $atom = shift;
1309  
1310 no warnings;
1311 $self->{'K'} = call_ja( $self->{'K'}, $atom->val );
1312 }
1313  
1314 sub list {
1315 my $self = shift;
1316 return undef unless defined $self->{'K'};
1317  
1318 return k2parray( $self->{'K'} );
1319 }
1320  
1321 sub av2k {
1322 my $self = shift;
1323 my ( $typ, $aref ) = @_;
1324  
1325 unless ( defined $typ && $typ > 0 && $typ < 20 ) {
1326 carp "Kx->av2k(self,x,typ) typ must be @TYP\n";
1327 return undef;
1328 }
1329  
1330 dor0( $self->{'K'} ) if defined $self->{'K'}; # release memory
1331  
1332 $self->{'K'} = newKarray( $typ, $aref );
1333 return $self;
1334 }
1335  
1336 sub listof {
1337 my $self = shift;
1338 my ( $x, $typ ) = @_;
1339  
1340 if ( $x <= 0 ) {
1341 carp "Kx->listof(self,x,typ) x=$x less than zero ";
1342 return undef;
1343 }
1344 unless ( defined $typ && $typ >= 0 && $typ < 20 ) {
1345 carp "Kx->listof(self,x,typ) typ must be @TYP\n";
1346 return undef;
1347 }
1348  
1349 my $k = Kx->new();
1350 $k->{'K'} = ktn( $typ, $x );
1351 return $k;
1352 }
1353  
1354 sub getbin {
1355 my $self = shift;
1356 my $ref = getKarraybinary( $self->{'K'}, 0, 0 );
1357 return $ref;
1358 }
1359  
1360 sub setbin {
1361 my $self = shift;
1362 my ($val) = @_;
1363  
1364 unless ( setKarraybinary( $self->{'K'}, 0, $val ) ) {
1365 carp "Kx->setbin error in binary copy\n";
1366 return 0;
1367 }
1368 return 1;
1369 }
1370  
1371 sub at {
1372 my $self = shift;
1373 my ( $x, @val ) = @_;
1374  
1375 # What type am I?
1376 my $mytype = kType( $self->{'K'} );
1377  
1378 # I need to be a list
1379 unless ( $mytype >= 0 ) {
1380 carp "Can't call Kx->at() on a non list K onject";
1381 return undef;
1382 }
1383  
1384 # If it is a set operation
1385 if ( defined $val[0] ) {
1386 my $k;
1387  
1388 # Want to store only Kdb+ structure directly or via an object for
1389 # mixed lists and scalars for simple lists.
1390 # Here we work out where the $k variable will come from
1391 if ( $mytype == 0 && ref( $val[0] ) eq 'KstructPtr' ) {
1392 $k = $val[0];
1393 }
1394 elsif ( $mytype == 0 && ref( $val[0] ) eq 'Kx' ) {
1395 $k = $val[0]->{'K'};
1396 }
1397 elsif ( $mytype > 0 && $#val == 2 ) # Assume a date yyyy,mm,dd
1398 {
1399 $k = ymd(@val);
1400 }
1401 elsif ( $mytype > 0 ) {
1402 $k = $val[0];
1403 }
1404 else {
1405 carp "Kx->at(pos,val) Invalid val type for this list type";
1406 return undef;
1407 }
1408  
1409 # Am I a List of K objects?
1410 if ( $mytype == 0 ) {
1411  
1412 # $k is of type K
1413 unless ( setKarraymixed( $self->{'K'}, $x, $k ) ) {
1414 carp "Kx->at(pos,val) pos=$x out of bounds? ";
1415 }
1416 return 0;
1417 }
1418 else # Simple list
1419 {
1420 # $k is a Perl scalar
1421 unless ( setKarraysimple( $self->{'K'}, $x, $k ) ) {
1422 carp "Kx->at(pos,val) type mismatch or pos=$x out of bounds";
1423 }
1424 return 0;
1425 }
1426 return undef;
1427 }
1428 else # A get operation
1429 {
1430 return getKarray( $self->{'K'}, $x );
1431 }
1432 }
1433  
1434 =head2 Utility Methods
1435  
1436 $k->dump0() will return a string describing the under lying K structure.
1437  
1438 Kx::dump($k) will print out the K structure of $k
1439  
1440 $sym = Kx::makesym("string") will convert a simple string into a quoted
1441 symbol suitable for usage in KDB+
1442  
1443 make_C() will convert its argument into a suitable string quoted
1444 as a KDB+ character list.
1445  
1446 my $c = Kx::make_C("now is\tthe \n time for \n help");
1447  
1448 There is also make_s():
1449  
1450 my $sym = Kx::make_s("a symbol"); # `$"a symbol"
1451 my $sym = Kx::make_s(undef); # a null symbol `
1452  
1453 =cut
1454  
1455 sub make_s {
1456 if ( !defined $_[0] ) {
1457 return '`';
1458 }
1459 return "`\$\"$_[0]\"";
1460 }
1461  
1462 sub make_C {
1463 if ( !defined $_[0] ) {
1464 return $NULL{'char'};
1465 }
1466 return '"c"$0x'
1467 . join( '', map { sprintf "%02x", $_ } unpack( "C*", $_[0] ) );
1468 }
1469  
1470 sub make_i {
1471 if ( !defined $_[0] ) {
1472 return $NULL{'int'};
1473 }
1474 return $_[0] + 0;
1475 }
1476  
1477 sub _getepoch {
1478 if ( $_[0] =~ /^now/io ) {
1479 return time;
1480 }
1481 elsif ( $_[0] =~ /^never/io ) {
1482 return 1999999999;
1483 }
1484 else {
1485 return $_[0];
1486 }
1487 }
1488  
1489 sub make_z_epoch_gmt {
1490 if ( !defined $_[0] ) {
1491 return $NULL{'datetime'};
1492 }
1493 return POSIX::strftime "%Y.%m.%dT%H:%M:%S", gmtime( _getepoch( $_[0] ) );
1494 }
1495  
1496 sub make_z_epoch_local {
1497 if ( !defined $_[0] ) {
1498 return $NULL{'datetime'};
1499 }
1500 return POSIX::strftime "%Y.%m.%dT%H:%M:%S", localtime( _getepoch( $_[0] ) );
1501 }
1502  
1503 sub dump0 {
1504 my $self = shift;
1505  
1506 return undef unless defined $self->{'K'};
1507 my $refcnt = kRefCnt( $self->{'K'} );
1508 my $type = kType( $self->{'K'} );
1509 my $att = kAtt( $self->{'K'} );
1510 my $num = kNum( $self->{'K'} );
1511 my $val = k2pscalar( $self->{'K'} );
1512  
1513 return
1514 "{Value: $val, RefCnt=>$refcnt, Type=>$type, Att=>$att, Num=>$num}\n";
1515  
1516 }
1517  
1518 sub dump {
1519 my $k = shift;
1520  
1521 return undef unless defined $k;
1522  
1523 my $refcnt = kRefCnt($k);
1524 my $type = kType($k);
1525 my $att = kAtt($k);
1526 my $num = kNum($k);
1527 my $val = k2pscalar($k) || 'no value';
1528  
1529 print "{Value: $val, RefCnt=>$refcnt, Type=>$type, Att=>$att, Num=>$num}\n";
1530  
1531 }
1532  
1533 sub DESTROY {
1534 my $self = shift;
1535 my $name = $self->{'name'} || return;
1536  
1537 return unless defined $self->{'K'};
1538 return unless ref( $self->{'K'} ) eq 'KstructPtr';
1539  
1540 dor0( $self->{'K'} );
1541  
1542 $DB{$name}{'count'}--;
1543 if ( $DB{$name}{'count'} <= 0 && exists $DB{$name}{'kdb'} ) {
1544 POSIX::close( $DB{$name}{'kdb'} );
1545 undef( $DB{$name} );
1546 }
1547 undef $self->{'K'};
1548 undef $self->{'COLS'};
1549 }
1550  
1551 sub dor0 {
1552 my $k = shift;
1553 unless ( defined $k ) {
1554 carp &whowasi;
1555 carp "Kx::dor0() must be called with an argument: ";
1556 }
1557 unless ( ref($k) eq 'KstructPtr' ) {
1558 carp &whowasi;
1559 carp "Kx::dor0() argument not a KstructPtr: ", ref($k), ": ";
1560 }
1561 r0($k);
1562 }
1563  
1564 #####################################################################
1565 # K List package #
1566 #####################################################################
1567 # A class implementing a tied ordinary array should define the following
1568 # methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE
1569 # and/or DESTROY.
1570 #
1571 # FETCHSIZE and STORESIZE are used to provide $#array and equivalent
1572 # "scalar(@array)" access.
1573 #
1574 # The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS
1575 #
1576  
1577 =head1 Kx::LIST
1578  
1579 You may wish to tie a Perl array to a Kdb+ variable. Well, you can do
1580 that as well. Try something like this:
1581  
1582 use Kx;
1583
1584 my %config = (
1585 host=>"localhost",
1586 port=>2222,
1587 userpass=>'user:pass', # optional
1588 type=>'symbol',
1589 list=>'d',
1590 create=>1
1591 );
1592 tie(@a, 'Kx::LIST', %config);
1593
1594 # push lost of stuff on an array
1595 my @array = (qw/aaaa bbbbb ccccc ddddddddd e f j h i j k l/) x 30000
1596 ;
1597 push(@a,@array);
1598 push(@a,@array);
1599 push(@a,@array);
1600 print "\@a has ", scalar(@a)," elements\n";
1601
1602 # Store
1603 $a[3] = "Help me";
1604 print "Elementt 3 is ",$a[3],"\n";
1605  
1606 All the functions defined in perltie for lists are included.
1607  
1608 Note: 'type' is a Kdb+ type as defined in Types below - it is the
1609 type for the array. Only simple types are allowed at the moment.
1610  
1611 =cut
1612  
1613 package Kx::LIST;
1614 $Kx::LIST::VERSION = '0.042';
1615 use 5.008;
1616 use strict;
1617 use warnings;
1618 use Carp;
1619 sub whowasi { ( caller(1) )[3] . '()' }
1620  
1621 sub TIEARRAY {
1622 carp &whowasi if $DEBUG;
1623 my $class = shift;
1624 my %opts = @_;
1625 my $d; # list
1626  
1627 my $name = $opts{'name'} || 'default';
1628 my $ref = { 'name' => $name };
1629 if ( defined $opts{'host'} ) {
1630 $DB{$name}{'host'} = $opts{'host'};
1631 }
1632 if ( defined $opts{'port'} ) {
1633 $DB{$name}{'port'} = $opts{'port'};
1634 }
1635 if ( defined $opts{'list'} ) {
1636 $ref->{'list'} = $opts{'list'};
1637 }
1638 if ( defined $opts{'create'} ) {
1639 $ref->{'create'} = 1;
1640 }
1641 my $type = $opts{'type'} || 'symbol';
1642 $ref->{'type'} = $type;
1643  
1644 return undef unless exists $CAST{$type};
1645 return undef
1646 unless defined $DB{$name}{'host'} && defined $DB{$name}{'port'};
1647 return undef unless defined $ref->{'list'};
1648  
1649 # Get hold of any previously defined connection handle
1650 if ( defined $DB{$name}{'kdb'} ) {
1651 $ref->{'kdb'} = $DB{$name}{'kdb'}; # no need for connect
1652 $DB{$name}{'count'}++;
1653 }
1654 else # get connected a new
1655 {
1656 if ( defined $DB{$name}{'userpass'} ) {
1657 $ref->{'kdb'} = Kx::khpu(
1658 $DB{$name}{'host'},
1659 $DB{$name}{'port'},
1660 $DB{$name}{'userpass'}
1661 );
1662 }
1663  
1664 # host, port only
1665 else {
1666 $ref->{'kdb'} = Kx::khp( $DB{$name}{'host'}, $DB{$name}{'port'} );
1667 }
1668 unless ( $ref->{'kdb'} > 0 ) {
1669 undef $ref->{'kdb'};
1670 return undef;
1671 }
1672 $DB{$name}{'kdb'} = $ref->{'kdb'};
1673 $DB{$name}{'count'}++;
1674 }
1675  
1676 # OK check if the variable already exists. If not then create it
1677 my $var = Kx::k2parray0( Kx::k( $ref->{'kdb'}, '\v' ) );
1678 $d = $ref->{'list'};
1679 if ( !grep( /^$d$/, @$var ) || defined $ref->{'create'} ) {
1680 my $r = Kx::k( $ref->{'kdb'}, "$d:()" );
1681 if ( $r == 0 ) {
1682 carp "Undefined K structure in TIELIST\n";
1683 return undef;
1684 }
1685 if ( Kx::kType($r) < 0 ) {
1686 carp "Kx::LIST error ", Kx::k2pscalar($r), "\n";
1687 return undef;
1688 }
1689 $ref->{'count'} = 0;
1690 }
1691  
1692 return bless $ref, $class;
1693 }
1694  
1695 sub FETCH {
1696 my $self = shift;
1697 my $i = shift;
1698  
1699 my $list = $self->{'list'};
1700 return undef if $i < 0 || $i >= $self->{'count'};
1701  
1702 $self->{'val'} = Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "$list\[$i\]" ) );
1703 return $self->{'val'};
1704 }
1705  
1706 sub STORE {
1707 my $self = shift;
1708 my $i = shift;
1709 my $val = shift;
1710 my $list = $self->{'list'};
1711  
1712 return undef if $i < 0;
1713 $self->EXTEND($i) if $i >= $self->{'count'};
1714  
1715 # Cast the value
1716 $val = $CAST{ $self->{'type'} } . $val;
1717 $val .= '"' if $self->{'type'} eq 'symbol';
1718  
1719 $self->{'val'} =
1720 Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "$list\[$i\]:$val" ) );
1721 return $self->{'val'};
1722 }
1723  
1724 sub FETCHSIZE {
1725 my $self = shift;
1726 my $list = $self->{'list'};
1727  
1728 $self->{'count'} = Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "count $list" ) );
1729 return $self->{'count'};
1730 }
1731  
1732 # STORESIZE this, count
1733 # Sets the total number of items in the tied array associated with
1734 # object this to be count. If this makes the array larger then
1735 # class's mapping of "undef" should be returned for new positions.
1736 # If the array becomes smaller then entries beyond count should be
1737 # deleted.
1738 #
1739 sub STORESIZE {
1740 my $self = shift;
1741 my $count = shift;
1742 my $list = $self->{'list'};
1743 my $oldsz = $self->{'count'};
1744  
1745 my $q = '';
1746 if ( $count < $oldsz ) {
1747  
1748 # Truncate the list
1749 $q = "$list:$count#$list";
1750 }
1751 elsif ( $count > $oldsz ) {
1752 my $null = $NULL{ $self->{'type'} };
1753 my $diff = $count - $oldsz;
1754 $q = "$list:$list,$diff#$null";
1755 }
1756 else {
1757 # nothing to do
1758 }
1759  
1760 my $r = Kx::k( $self->{'kdb'}, $q );
1761 Kx::dor0($r);
1762  
1763 $self->{'count'} = $count;
1764 }
1765  
1766 sub EXTEND {
1767 my $self = shift;
1768 my $count = shift;
1769 $self->STORESIZE($count);
1770 }
1771  
1772 sub CLEAR {
1773 my $self = shift;
1774 my $list = $self->{'list'};
1775 $self->{'count'} = 0;
1776  
1777 my $q = "$list:()";
1778 my $r = Kx::k( $self->{'kdb'}, $q );
1779 Kx::dor0($r);
1780 }
1781  
1782 sub UNTIE {
1783 carp &whowasi if $DEBUG;
1784 my $self = shift;
1785 Kx::DESTROY($self);
1786 }
1787  
1788 sub POP {
1789 my $self = shift;
1790 my $list = $self->{'list'};
1791  
1792 return undef if $self->{'count'} <= 0;
1793  
1794 $self->{'count'}--;
1795  
1796 # Get value
1797 my $q = "-1#$list";
1798 $self->{'val'} = Kx::k2parray0( Kx::k( $self->{'kdb'}, $q ) );
1799  
1800 # reduce list
1801 $q = "$list:-1_$list";
1802 my $r = Kx::k( $self->{'kdb'}, $q );
1803 Kx::dor0($r);
1804  
1805 return $self->{'val'}[0];
1806 }
1807  
1808 sub PUSH {
1809 my $self = shift;
1810 my @arr = @_;
1811 my $list = $self->{'list'};
1812 my $cast = $CAST{ $self->{'type'} };
1813  
1814 my $issymbol = $self->{'type'} eq 'symbol';
1815  
1816 # Do N at a time
1817 while (@arr) {
1818 my $q = "$list:$list,(";
1819 for my $v ( splice( @arr, 0, 500 ) ) {
1820 $v = $cast . $v;
1821 $v .= '"' if $issymbol;
1822 $q .= "$v;";
1823 }
1824 chop($q);
1825 $q .= ')';
1826 my $r = Kx::k( $self->{'kdb'}, $q );
1827 Kx::dor0($r);
1828 }
1829  
1830 return $self->FETCHSIZE();
1831 }
1832  
1833 sub SHIFT {
1834 my $self = shift;
1835 my $list = $self->{'list'};
1836  
1837 return undef if $self->{'count'} <= 0;
1838  
1839 $self->{'count'}--;
1840  
1841 my $q = "1#$list";
1842 $self->{'val'} = Kx::k2parray0( Kx::k( $self->{'kdb'}, $q ) );
1843 $q = "$list:1_$list";
1844 my $r = Kx::k( $self->{'kdb'}, $q );
1845 Kx::dor0($r);
1846 return $self->{'val'}[0];
1847 }
1848  
1849 sub UNSHIFT {
1850 my $self = shift;
1851 my @arr = @_;
1852 my $list = $self->{'list'};
1853 my $cast = $CAST{ $self->{'type'} };
1854  
1855 my $issymbol = $self->{'type'} eq 'symbol';
1856  
1857 # Do N at a time
1858 while (@arr) {
1859 my $q = "$list:(";
1860 my $len = @arr;
1861 $len = 500 if $len > 500;
1862 for my $v ( splice( @arr, -$len ) ) {
1863 $v = $cast . $v;
1864 $v .= '"' if $issymbol;
1865 $q .= "$v;";
1866 }
1867 chop($q);
1868 $q .= "),$list";
1869 my $r = Kx::k( $self->{'kdb'}, $q );
1870 Kx::dor0($r);
1871 }
1872  
1873 return $self->FETCHSIZE();
1874 }
1875  
1876 # SPLICE this, offset, length, LIST
1877 # Perform the equivalent of "splice" on the array.
1878 #
1879 # offset is optional and defaults to zero, negative values count back
1880 # from the end of the array.
1881 #
1882 # length is optional and defaults to rest of the array.
1883 #
1884 # LIST may be empty.
1885 #
1886 # Returns a list of the original length elements at offset.
1887 sub SPLICE {
1888 my $self = shift;
1889 my $i = shift || 0;
1890 my $len = shift || $self->{'count'} - $i;
1891 my @arr = @_;
1892  
1893 my $list = $self->{'list'};
1894 my $count = $self->{'count'};
1895  
1896 # Sanity check on $i and $len
1897 return undef if abs($i) >= $count;
1898 return undef if $len <= 0;
1899 if ( $i < 0 ) {
1900 $len = abs($i) if $len > abs($i); # Clamp length if too big
1901 $i = $count + $i + 1;
1902 }
1903 return undef if ( $len + $i ) > $count;
1904  
1905 my $q;
1906  
1907 # First get hold of the old data to return
1908 $q = "$list\[(til $len) + $i\]";
1909 my $aref = Kx::k2parray0( Kx::k( $self->{'kdb'}, $q ) );
1910  
1911 if (@arr) {
1912  
1913 # Now add the new stuff
1914 $q = "$list\[(til $len) + $i\]:(";
1915 my $cast = $CAST{ $self->{'type'} };
1916  
1917 my $issymbol = $self->{'type'} eq 'symbol';
1918  
1919 for ( my $j = 0 ; $j < $len && $j <= $#arr ; $j++ ) {
1920 my $v = $cast . $arr[$j];
1921 $v .= '"' if $issymbol;
1922 $q .= "$v;";
1923 }
1924 chop($q);
1925 $q .= ')';
1926 my $r = Kx::k( $self->{'kdb'}, $q );
1927 Kx::dor0($r);
1928 }
1929 else {
1930 # delete the slice. from 0 to $i to $j cut the list and join the
1931 # front and back bits back together
1932 my $j = $i + $len;
1933 $q = "$list:raze (0 $i $j\_$list)[0 2]";
1934 my $r = Kx::k( $self->{'kdb'}, $q );
1935 Kx::dor0($r);
1936 }
1937 return @$aref;
1938 }
1939  
1940 sub DELETE {
1941 my $self = shift;
1942 my $i = shift;
1943 my $list = $self->{'list'};
1944  
1945 return undef if $i < 0;
1946 $self->EXTEND($i) if $i >= $self->{'count'};
1947  
1948 # A null value
1949 my $val = $NULL{ $self->{'type'} };
1950  
1951 $self->{'val'} =
1952 Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "$list\[$i\]:$val" ) );
1953 return $self->{'val'};
1954 }
1955  
1956 sub EXISTS {
1957 my $self = shift;
1958 my $i = shift;
1959  
1960 return 0 if $i < 0 || $i >= $self->{'count'};
1961 my $list = $self->{'list'};
1962 my $null = $NULL{ $self->{'type'} };
1963 return Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "not $list\[$i\]=$null" ) );
1964 }
1965  
1966 package Kx::HASH;
1967 #####################################################################
1968 # K Hash package #
1969 #####################################################################
1970 $Kx::HASH::VERSION = '0.042';
1971 =head1 Kx::HASH
1972  
1973 You may wish to tie a Perl hash to a Kdb+ variable. Well, you can do
1974 that as well. Try something like this:
1975  
1976 use Kx;
1977  
1978 my %config = (
1979 host=>"localhost",
1980 port=>2222,
1981 userpass=>'user:pass', # optional
1982 ktype=>'symbol',
1983 vtype=>'int',
1984 dict=>'x',
1985 create=>1
1986 );
1987 tie(%x, 'Kx::HASH', %config);
1988
1989 print "Size of hash x is :". scalar %x ."\n";
1990 for(0..5) {
1991 $x{"a$_"} = $_;
1992 }
1993
1994 %y = %x;
1995
1996 for(0..5) {
1997 print $y{"a$_"}," " if exists $y{"a$_"};
1998 }
1999 print "\n";
2000
2001 while(($k,$v) = each %x) {
2002 print "Key=>$k is $v\n";
2003 }
2004 untie(%x);
2005  
2006 All the functions defined in perltie for hashs are included.
2007  
2008 Note: ktype is a Kdb+ type as defined in Types below - it is the
2009 'key' type for the hash. vtype is also defined in Types - it is the
2010 value type. Only simple types are allowed at the moment.
2011  
2012 =cut
2013  
2014 use 5.008;
2015 use strict;
2016 use warnings;
2017 use Carp;
2018 sub whowasi { ( caller(1) )[3] . '()' }
2019  
2020 sub DESTROY {
2021 carp &whowasi if $DEBUG;
2022 my $self = shift;
2023 dor0( $self->{'K'} ) if defined $self->{'K'}; # release memory
2024 }
2025  
2026 sub TIEHASH {
2027 carp &whowasi if $DEBUG;
2028 my $class = shift;
2029 my %opts = @_;
2030 my $d; # Dictionary
2031  
2032 return undef unless defined $opts{'dict'};
2033  
2034 my $name = 'default';
2035 $name = $opts{'name'} if defined $opts{'name'};
2036  
2037 my $ref = { 'name' => $name };
2038 if ( defined $opts{'host'} ) {
2039 $DB{$name}{'host'} = $opts{'host'};
2040 }
2041 if ( defined $opts{'port'} ) {
2042 $DB{$name}{'port'} = $opts{'port'};
2043 }
2044 if ( defined $opts{'check_for_errors'} ) {
2045 $DB{$name}{'check_for_errors'} = $opts{'check_for_errors'};
2046 }
2047  
2048 if ( defined $opts{'dict'} ) {
2049 $ref->{'dict'} = $opts{'dict'};
2050 }
2051 if ( defined $opts{'create'} ) {
2052 $ref->{'create'} = 1;
2053 }
2054 my $ktype = $opts{'ktype'} || 'symbol';
2055 my $vtype = $opts{'vtype'} || 'symbol';
2056 $ref->{'ktype'} = $ktype;
2057 $ref->{'vtype'} = $vtype;
2058  
2059 # Get hold of any previously defined connection handle
2060 if ( defined $DB{$name}{'kdb'} ) {
2061 $ref->{'kdb'} = $DB{$name}{'kdb'}; # no need for connect
2062 $DB{$name}{'count'}++;
2063 }
2064 else # get connected a new
2065 {
2066 if ( defined $DB{$name}{'userpass'} ) {
2067 $ref->{'kdb'} = Kx::khpu(
2068 $DB{$name}{'host'},
2069 $DB{$name}{'port'},
2070 $DB{$name}{'userpass'}
2071 );
2072 }
2073  
2074 # host, port only
2075 else {
2076 $ref->{'kdb'} = Kx::khp( $DB{$name}{'host'}, $DB{$name}{'port'} );
2077 }
2078 unless ( $ref->{'kdb'} > 0 ) {
2079 undef $ref->{'kdb'};
2080 return undef;
2081 }
2082 $DB{$name}{'kdb'} = $ref->{'kdb'};
2083 $DB{$name}{'count'}++;
2084 }
2085  
2086 # OK check if the variable already exists. If not then create it
2087 my $var = Kx::k2parray0( Kx::k( $ref->{'kdb'}, '\v' ) );
2088 $d = $ref->{'dict'};
2089 if ( !grep( /^$d$/, @$var ) || defined $ref->{'create'} ) {
2090  
2091 # Need to create it.
2092 my $r = Kx::k( $ref->{'kdb'}, "$d:(`$ktype\$())!`$vtype\$()" );
2093 if ( $r == 0 ) {
2094 carp "Undefined K structure in TIEHASH\n";
2095 return undef;
2096 }
2097 if ( Kx::kType($r) < 0 ) {
2098 carp "K error ", Kx::k2pscalar($r), "\n";
2099 return undef;
2100 }
2101 }
2102  
2103 return bless $ref, $class;
2104 }
2105  
2106 sub FETCH {
2107 carp &whowasi if $DEBUG;
2108 my $self = shift;
2109 my $key = shift;
2110  
2111 my $dict = $self->{'dict'};
2112 my $ktype = $self->{'ktype'};
2113  
2114 # Cast key to right type
2115 $key = $CAST{$ktype} . $key;
2116 $key .= '"' if $ktype eq 'symbol';
2117 $self->{'val'} = Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "$dict $key" ) );
2118 return $self->{'val'};
2119 }
2120  
2121 sub STORE {
2122 carp &whowasi if $DEBUG;
2123 my $self = shift;
2124 my $key = shift;
2125 my $val = shift;
2126  
2127 my $dict = $self->{'dict'};
2128 my $ktype = $self->{'ktype'};
2129 my $vtype = $self->{'vtype'};
2130  
2131 # Cast key and value to right type
2132 if ( $ktype eq "symbol" ) {
2133 $key = '`$"' . $key . '"';
2134 }
2135 else {
2136 $key = $CAST{$ktype} . $key;
2137 }
2138 if ( $vtype eq "symbol" ) {
2139 $val = '`$"' . $val . '"';
2140 }
2141 else {
2142 $val = $CAST{$vtype} . $val;
2143 }
2144 my $r = Kx::k( $self->{'kdb'}, "$dict" . "[$key]:$val" );
2145 Kx::dor0($r);
2146 return;
2147 }
2148  
2149 sub DELETE {
2150 carp &whowasi if $DEBUG;
2151 my $self = shift;
2152 my $key = shift;
2153  
2154 my $dict = $self->{'dict'};
2155 $self->{'K'} = Kx::k( $self->{'kdb'}, ".[`$dict;();_;$key]" );
2156 Kx::dor0( $self->{'K'} );
2157 return 1;
2158 }
2159  
2160 sub CLEAR {
2161 carp &whowasi if $DEBUG;
2162 my $self = shift;
2163  
2164 my $d = $self->{'dict'};
2165 my $ktype = $self->{'ktype'};
2166 my $vtype = $self->{'vtype'};
2167  
2168 my $r = Kx::k( $self->{'kdb'}, "$d:(`$ktype\$())!`$vtype\$()" );
2169 Kx::dor0($r);
2170 return 1;
2171 }
2172  
2173 sub EXISTS {
2174 carp &whowasi if $DEBUG;
2175 my $self = shift;
2176 my $key = shift;
2177  
2178 my $dict = $self->{'dict'};
2179 my $ktype = $self->{'ktype'};
2180  
2181 # Cast key to right type
2182 $key = $CAST{$ktype} . $key;
2183 $key .= '"' if $ktype eq 'symbol';
2184 my $null = $NULL{ $self->{'vtype'} };
2185 $self->{'K'} = Kx::k( $self->{'kdb'}, "not $dict" . "[$key]=$null" );
2186 return Kx::k2pscalar0( $self->{'K'} );
2187 }
2188  
2189 sub FIRSTKEY {
2190 carp &whowasi if $DEBUG;
2191 my $self = shift;
2192  
2193 my $dict = $self->{'dict'};
2194 $self->{'i'} = 0;
2195 $self->{'count'} = Kx::k2pscalar0( Kx::k( $self->{'kdb'}, "count $dict" ) );
2196 $self->{'K'} = Kx::k( $self->{'kdb'}, "(key $dict)[0]" );
2197 return Kx::k2pscalar0( $self->{'K'} );
2198 }
2199  
2200 sub NEXTKEY {
2201 carp &whowasi if $DEBUG;
2202 my $self = shift;
2203  
2204 my $dict = $self->{'dict'};
2205 $self->{'i'}++;
2206 return undef if $self->{'i'} >= $self->{'count'};
2207  
2208 my $i = $self->{'i'};
2209 $self->{'K'} = Kx::k( $self->{'kdb'}, "(key $dict)[$i]" );
2210 return Kx::k2pscalar0( $self->{'K'} );
2211 }
2212  
2213 sub SCALAR {
2214 carp &whowasi if $DEBUG;
2215 my $self = shift;
2216  
2217 my $dict = $self->{'dict'};
2218 $self->{'K'} = Kx::k( $self->{'kdb'}, "count $dict" );
2219 return Kx::k2pscalar0( $self->{'K'} );
2220 }
2221  
2222 sub UNTIE {
2223 my $self = shift;
2224 Kx::DESTROY($self);
2225 }
2226  
2227 package Kx;
2228  
2229 # Preloaded methods go here.
2230  
2231 # Autoload methods go after =cut, and are processed by the autosplit program.
2232  
2233 1;
2234  
2235 __END__