lib/Kx.pm untested

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