1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
|
use 5.006;
use strict;
use warnings;
package Hash::Ordered;
# ABSTRACT: A fast, pure-Perl ordered hash class
our $VERSION = '0.014';
use Carp ();
use constant {
_DATA => 0, # unordered data
_KEYS => 1, # ordered keys
_INDX => 2, # index into _KEYS (on demand)
_OFFS => 3, # index offset for optimized shift/unshift
_GCNT => 4, # garbage count
_ITER => 5, # for tied hash support
};
use constant {
_INDEX_THRESHOLD => 25, # max size before indexing/tombstone deletion
_TOMBSTONE => \1, # ref to arbitrary scalar
};
# 'overloading.pm' not available until 5.10.1 so emulate with Scalar::Util
BEGIN {
if ( $] gt '5.010000' ) {
## no critic
eval q{
sub _stringify { no overloading; "$_[0]" }
sub _numify { no overloading; 0+$_[0] }
};
die $@ if $@; # uncoverable branch true
}
else {
## no critic
eval q{
require Scalar::Util;
sub _stringify { sprintf("%s=ARRAY(0x%x)",ref($_[0]),Scalar::Util::refaddr($_[0])) }
sub _numify { Scalar::Util::refaddr($_[0]) }
};
die $@ if $@; # uncoverable branch true
}
}
use overload
q{""} => \&_stringify,
q{0+} => \&_numify,
q{bool} => sub { !!scalar %{ $_[0]->[_DATA] } },
fallback => 1;
#pod =method new
#pod
#pod $oh = Hash::Ordered->new;
#pod $oh = Hash::Ordered->new( @pairs );
#pod
#pod Constructs an object, with an optional list of key-value pairs.
#pod
#pod The position of a key corresponds to the first occurrence in the list, but
#pod the value will be updated if the key is seen more than once.
#pod
#pod Current API available since 0.009.
#pod
#pod =cut
sub new {
my $class = shift;
Carp::croak("new() requires key-value pairs") unless @_ % 2 == 0;
my ( %data, @keys, $k );
while (@_) {
# must stringify keys for _KEYS array
$k = shift;
push @keys, "$k" unless exists $data{$k};
$data{$k} = shift;
}
return bless [ \%data, \@keys, undef, 0, 0 ], $class;
}
#pod =method clone
#pod
#pod $oh2 = $oh->clone;
#pod $oh2 = $oh->clone( @keys );
#pod
#pod Creates a shallow copy of an ordered hash object. If no arguments are
#pod given, it produces an exact copy. If a list of keys is given, the new
#pod object includes only those keys in the given order. Keys that aren't
#pod in the original will have the value C<undef>.
#pod
#pod =cut
sub clone {
my $self = CORE::shift;
my $clone;
if (@_) {
my %subhash;
@subhash{@_} = @{ $self->[_DATA] }{@_};
$clone = [ \%subhash, [ map "$_", @_ ], undef, 0, 0 ];
}
elsif ( $self->[_INDX] ) {
$clone =
[ { %{ $self->[_DATA] } }, [ grep !ref($_), @{ $self->[_KEYS] } ], undef, 0, 0 ];
}
else {
$clone =
[ { %{ $self->[_DATA] } }, [ @{ $self->[_KEYS] } ], undef, 0, 0 ];
}
return bless $clone, ref $self;
}
#pod =method keys
#pod
#pod @keys = $oh->keys;
#pod $size = $oh->keys;
#pod
#pod In list context, returns the ordered list of keys. In scalar context, returns
#pod the number of elements.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub keys {
my ($self) = @_;
return wantarray
? ( grep !ref($_), @{ $self->[_KEYS] } )
: @{ $self->[_KEYS] } - $self->[_GCNT];
}
#pod =method values
#pod
#pod @values = $oh->values;
#pod @values = $oh->values( @keys );
#pod
#pod Returns an ordered list of values. If no arguments are given, returns
#pod the ordered values of the entire hash. If a list of keys is given, returns
#pod values in order corresponding to those keys. If a key does not exist, C<undef>
#pod will be returned for that value.
#pod
#pod In scalar context, returns the number of elements.
#pod
#pod Current API available since 0.006.
#pod
#pod =cut
sub values {
my $self = CORE::shift;
return
wantarray
? ( map { $self->[_DATA]{$_} } ( @_ ? @_ : grep !ref($_), @{ $self->[_KEYS] } ) )
: @{ $self->[_KEYS] } - $self->[_GCNT];
}
#pod =method get
#pod
#pod $value = $oh->get("some key");
#pod
#pod Returns the value associated with the key, or C<undef> if it does not exist in
#pod the hash.
#pod
#pod =cut
sub get {
return $_[0]->[_DATA]{ $_[1] };
}
#pod =method set
#pod
#pod $oh->set("some key" => "some value");
#pod
#pod Associates a value with a key and returns the value. If the key does not
#pod already exist in the hash, it will be added at the end.
#pod
#pod =cut
sub set {
my ( $self, $key ) = @_; # don't copy $_[2] in case it's large
if ( !exists $self->[_DATA]{$key} ) {
my $keys = $self->[_KEYS];
if ( my $indx = $self->[_INDX] ) {
$indx->{$key} = @$keys ? $indx->{ $keys->[-1] } + 1 : 0;
}
CORE::push @{ $self->[_KEYS] }, "$key"; # stringify key
}
return $self->[_DATA]{$key} = $_[2];
}
#pod =method exists
#pod
#pod if ( $oh->exists("some key") ) { ... }
#pod
#pod Test if some key exists in the hash (without creating it).
#pod
#pod =cut
sub exists {
return exists $_[0]->[_DATA]{ $_[1] };
}
#pod =method delete
#pod
#pod $value = $oh->delete("some key");
#pod
#pod Removes a key-value pair from the hash and returns the value.
#pod
#pod =cut
sub delete {
my ( $self, $key ) = @_;
if ( exists $self->[_DATA]{$key} ) {
my $keys = $self->[_KEYS];
# JIT an index if hash is "large"
if ( !$self->[_INDX] && @$keys > _INDEX_THRESHOLD ) {
my %indx;
$indx{ $keys->[$_] } = $_ for 0 .. $#{$keys};
$self->[_INDX] = \%indx;
}
if ( $self->[_INDX] ) {
# tombstone
$keys->[ delete( $self->[_INDX]{$key} ) + $self->[_OFFS] ] = _TOMBSTONE;
# GC keys and remove index if more than half keys are tombstone.
# Index will be recreated if needed on next delete
if ( ++$self->[_GCNT] > @$keys / 2 ) {
@{ $self->[_KEYS] } = grep !ref($_), @{ $self->[_KEYS] };
$self->[_INDX] = undef;
$self->[_OFFS] = 0;
$self->[_GCNT] = 0;
}
# or maybe garbage collect start of list
elsif ( ref( $keys->[0] ) ) {
my $i = 0;
$i++ while ref( $keys->[$i] );
splice @$keys, 0, $i;
$self->[_GCNT] -= $i;
$self->[_OFFS] -= $i;
}
# or maybe garbage collect end of list
elsif ( ref( $keys->[-1] ) ) {
my $i = $#{$keys};
$i-- while ref( $keys->[$i] );
$self->[_GCNT] -= $#{$keys} - $i;
splice @$keys, $i + 1;
}
}
else {
my $i;
for ( 0 .. $#{$keys} ) {
if ( $keys->[$_] eq $key ) { $i = $_; last; }
}
splice @$keys, $i, 1;
}
return delete $self->[_DATA]{$key};
}
return undef; ## no critic
}
#pod =method clear
#pod
#pod $oh->clear;
#pod
#pod Removes all key-value pairs from the hash. Returns undef in scalar context
#pod or an empty list in list context.
#pod
#pod Current API available since 0.003.
#pod
#pod =cut
sub clear {
my ($self) = @_;
@$self = ( {}, [], undef, 0, 0 );
return;
}
#pod =method push
#pod
#pod $oh->push( one => 1, two => 2);
#pod
#pod Add a list of key-value pairs to the end of the ordered hash. If a key already
#pod exists in the hash, it will be deleted and re-inserted at the end with the new
#pod value.
#pod
#pod Returns the number of keys after the push is complete.
#pod
#pod =cut
sub push {
my $self = CORE::shift;
my ( $data, $keys ) = @$self;
while (@_) {
my ( $k, $v ) = splice( @_, 0, 2 );
$self->delete($k) if exists $data->{$k};
$data->{$k} = $v;
if ( my $indx = $self->[_INDX] ) {
$indx->{$k} = @$keys ? $indx->{ $keys->[-1] } + 1 : 0;
}
CORE::push @$keys, "$k"; # stringify keys
}
return @$keys - $self->[_GCNT];
}
#pod =method pop
#pod
#pod ($key, $value) = $oh->pop;
#pod $value = $oh->pop;
#pod
#pod Removes and returns the last key-value pair in the ordered hash.
#pod In scalar context, only the value is returned. If the hash is empty,
#pod the returned key and value will be C<undef>.
#pod
#pod =cut
sub pop {
my ($self) = @_;
if ( $self->[_INDX] ) {
my $key = $self->[_KEYS][-1];
return $key, $self->delete($key);
}
else {
my $key = CORE::pop @{ $self->[_KEYS] };
return defined($key) ? ( $key, delete $self->[_DATA]{$key} ) : ();
}
}
#pod =method unshift
#pod
#pod $oh->unshift( one => 1, two => 2 );
#pod
#pod Adds a list of key-value pairs to the beginning of the ordered hash. If a key
#pod already exists, it will be deleted and re-inserted at the beginning with the
#pod new value.
#pod
#pod Returns the number of keys after the unshift is complete.
#pod
#pod =cut
sub unshift {
my $self = CORE::shift;
my ( $data, $keys ) = @$self;
while (@_) {
my ( $k, $v ) = splice( @_, -2, 2 );
$self->delete($k) if exists $data->{$k};
$data->{$k} = $v;
CORE::unshift @$keys, "$k"; # stringify keys
$self->[_INDX]{$k} = -( ++$self->[_OFFS] ) if $self->[_INDX];
}
return @$keys - $self->[_GCNT];
}
#pod =method shift
#pod
#pod ($key, $value) = $oh->shift;
#pod $value = $oh->shift;
#pod
#pod Removes and returns the first key-value pair in the ordered hash.
#pod In scalar context, only the value is returned. If the hash is empty,
#pod the returned key and value will be C<undef>.
#pod
#pod =cut
sub shift {
my ($self) = @_;
if ( $self->[_INDX] ) {
my $key = $self->[_KEYS][0];
return $key, $self->delete($key);
}
else {
my $key = CORE::shift @{ $self->[_KEYS] };
return defined($key) ? ( $key, delete $self->[_DATA]{$key} ) : ();
}
}
#pod =method merge
#pod
#pod $oh->merge( one => 1, two => 2 );
#pod
#pod Merges a list of key-value pairs into the ordered hash. If a key already
#pod exists, its value is replaced. Otherwise, the key-value pair is added at
#pod the end of the hash.
#pod
#pod =cut
sub merge {
my $self = CORE::shift;
while (@_) {
my ( $k, $v ) = splice( @_, 0, 2 );
if ( !exists $self->[_DATA]{$k} ) {
my $size = CORE::push @{ $self->[_KEYS] }, "$k"; # stringify key
$self->[_INDX]{$k} = $size - 1 if $self->[_INDX];
}
$self->[_DATA]{$k} = $v;
}
return @{ $self->[_KEYS] } - $self->[_GCNT];
}
#pod =method as_list
#pod
#pod @pairs = $oh->as_list;
#pod @pairs = $oh->as_list( @keys );
#pod
#pod Returns an ordered list of key-value pairs. If no arguments are given, all
#pod pairs in the hash are returned. If a list of keys is given, the returned list
#pod includes only those key-value pairs in the given order. Keys that aren't in
#pod the original will have the value C<undef>.
#pod
#pod =cut
sub as_list {
my $self = CORE::shift;
return
map { ; $_ => $self->[_DATA]{$_} }
( @_ ? @_ : grep !ref($_), @{ $self->[_KEYS] } );
}
#pod =method iterator
#pod
#pod $iter = $oh->iterator;
#pod $iter = $oh->iterator( reverse $oh->keys ); # reverse
#pod
#pod while ( my ($key,$value) = $iter->() ) { ... }
#pod
#pod Returns a code reference that returns a single key-value pair (in order) on
#pod each invocation, or the empty list if all keys are visited.
#pod
#pod If no arguments are given, the iterator walks the entire hash in order. If a
#pod list of keys is provided, the iterator walks the hash in that order. Unknown
#pod keys will return C<undef>.
#pod
#pod The list of keys to return is set when the iterator is generator. Keys added
#pod later will not be returned. Subsequently deleted keys will return C<undef>
#pod for the value.
#pod
#pod =cut
# usually we avoid copying keys in @_; here we must for the closure
sub iterator {
my ( $self, @keys ) = @_;
@keys = grep !ref($_), @{ $self->[_KEYS] } unless @keys;
my $data = $self->[_DATA];
return sub {
return unless @keys;
my $key = CORE::shift(@keys);
return ( $key => $data->{$key} );
};
}
#pod =method preinc
#pod
#pod $oh->preinc($key); # like ++$hash{$key}
#pod
#pod This method is sugar for incrementing a key without having to call C<set> and
#pod C<get> explicitly. It returns the new value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub preinc {
return ++$_[0]->[_DATA]{ $_[1] };
}
#pod =method postinc
#pod
#pod $oh->postinc($key); # like $hash{$key}++
#pod
#pod This method is sugar for incrementing a key without having to call C<set> and
#pod C<get> explicitly. It returns the old value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub postinc {
return $_[0]->[_DATA]{ $_[1] }++;
}
#pod =method predec
#pod
#pod $oh->predec($key); # like --$hash{$key}
#pod
#pod This method is sugar for decrementing a key without having to call C<set> and
#pod C<get> explicitly. It returns the new value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub predec {
return --$_[0]->[_DATA]{ $_[1] };
}
#pod =method postdec
#pod
#pod $oh->postdec($key); # like $hash{$key}--
#pod
#pod This method is sugar for decrementing a key without having to call C<set> and
#pod C<get> explicitly. It returns the old value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub postdec {
return $_[0]->[_DATA]{ $_[1] }--;
}
#pod =method add
#pod
#pod $oh->add($key, $n); # like $hash{$key} += $n
#pod
#pod This method is sugar for adding a value to a key without having to call
#pod C<set> and C<get> explicitly. With no value to add, it is treated as "0".
#pod It returns the new value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub add {
return $_[0]->[_DATA]{ $_[1] } += $_[2] || 0;
}
#pod =method subtract
#pod
#pod $oh->subtract($key, $n); # like $hash{$key} -= $n
#pod
#pod This method is sugar for subtracting a value from a key without having to call
#pod C<set> and C<get> explicitly. With no value to subtract, it is treated as "0".
#pod It returns the new value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub subtract {
return $_[0]->[_DATA]{ $_[1] } -= $_[2] || 0;
}
#pod =method concat
#pod
#pod $oh->concat($key, $str); # like $hash{$key} .= $str
#pod
#pod This method is sugar for concatenating a string onto the value of a key without
#pod having to call C<set> and C<get> explicitly. It returns the new value. If the
#pod value to append is not defined, no concatenation is done and no warning is
#pod given.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub concat {
if ( defined $_[2] ) {
return $_[0]->[_DATA]{ $_[1] } .= $_[2];
}
else {
return $_[0]->[_DATA]{ $_[1] };
}
}
#pod =method or_equals
#pod
#pod $oh->or_equals($key, $str); # like $hash{$key} ||= $str
#pod
#pod This method is sugar for assigning to a key if the existing value is false
#pod without having to call C<set> and C<get> explicitly. It returns the new value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub or_equals {
my ($self,$key) = @_;
if ( my $val = $self->get($key) ) {
return $val;
}
return $self->set($key,$_[2]);
}
#pod =method dor_equals
#pod
#pod $oh->dor_equals($key, $str); # like $hash{$key} //= $str
#pod
#pod This method is sugar for assigning to a key if the existing value is not
#pod defined without having to call C<set> and C<get> explicitly. It returns the new
#pod value.
#pod
#pod Current API available since 0.005.
#pod
#pod =cut
sub dor_equals {
my ($self,$key) = @_;
if ( defined( my $val = $self->get($key) ) ) {
return $val;
}
return $self->set($key,$_[2]);
}
#--------------------------------------------------------------------------#
# tied hash support -- slower, but I maybe some thing are more succinct
#--------------------------------------------------------------------------#
{
no strict 'refs';
*{ __PACKAGE__ . '::TIEHASH' } = \&new;
*{ __PACKAGE__ . '::STORE' } = \&set;
*{ __PACKAGE__ . '::FETCH' } = \&get;
*{ __PACKAGE__ . '::EXISTS' } = \&exists;
*{ __PACKAGE__ . '::DELETE' } = \&delete;
*{ __PACKAGE__ . '::CLEAR' } = \&clear;
}
sub FIRSTKEY {
my ($self) = @_;
my @keys = grep !ref($_), @{ $self->[_KEYS] };
$self->[_ITER] = sub {
return unless @keys;
return CORE::shift(@keys);
};
return $self->[_ITER]->();
}
sub NEXTKEY {
return defined( $_[0]->[_ITER] ) ? $_[0]->[_ITER]->() : undef;
}
sub SCALAR {
return scalar %{ $_[0]->[_DATA] };
}
1;
# vim: ts=4 sts=4 sw=4 et:
__END__
=pod
=encoding UTF-8
=head1 NAME
Hash::Ordered - A fast, pure-Perl ordered hash class
=head1 VERSION
version 0.014
=head1 SYNOPSIS
use Hash::Ordered;
my $oh = Hash::Ordered->new( a => 1 );
$oh->get( 'a' );
$oh->set( 'a' => 2 );
$oh->exists( 'a' );
$val = $oh->delete( 'a' );
@keys = $oh->keys;
@vals = $oh->values;
@pairs = $oh->as_list
$oh->push( c => 3, d => 4 );
$oh->unshift( e => 5, f => 6 );
( $k, $v ) = $oh->pop;
( $k, $v ) = $oh->shift;
$iter = $oh->iterator;
while( ( $k, $v ) = $iter->() ) { ... }
$copy = $oh->clone;
$subset = $oh->clone( qw/c d/ );
$reversed = $oh->clone( reverse $oh->keys );
@value_slice = $oh->values( qw/c f/ ); # qw/3 6/
@pairs_slice = $oh->as_list( qw/f e/ ); # qw/f 6 e 5/
$oh->postinc( 'a' ); # like $oh{a}++
$oh->add( 'a', 5 ); # like $oh{a} += 5
$oh->concat( 'a', 'hello' ); # like $oh{a} .= 'hello'
$oh->or_equals( 'g', '23' ); # like $oh{g} ||= 23
$oh->dor_equals( 'g', '23' ); # like $oh{g} //= 23
=head1 DESCRIPTION
This module implements an ordered hash, meaning that it associates keys with
values like a Perl hash, but keeps the keys in a consistent order. Because it
is implemented as an object and manipulated with method calls, it is much
slower than a Perl hash. This is the cost of keeping order.
However, compared to other B<ordered> hash implementations, Hash::Ordered is
optimized for getting and setting individual elements and is generally faster
at most other tasks as well. For specific details, see
L<Hash::Ordered::Benchmarks>.
=head1 METHODS
=head2 new
$oh = Hash::Ordered->new;
$oh = Hash::Ordered->new( @pairs );
Constructs an object, with an optional list of key-value pairs.
The position of a key corresponds to the first occurrence in the list, but
the value will be updated if the key is seen more than once.
Current API available since 0.009.
=head2 clone
$oh2 = $oh->clone;
$oh2 = $oh->clone( @keys );
Creates a shallow copy of an ordered hash object. If no arguments are
given, it produces an exact copy. If a list of keys is given, the new
object includes only those keys in the given order. Keys that aren't
in the original will have the value C<undef>.
=head2 keys
@keys = $oh->keys;
$size = $oh->keys;
In list context, returns the ordered list of keys. In scalar context, returns
the number of elements.
Current API available since 0.005.
=head2 values
@values = $oh->values;
@values = $oh->values( @keys );
Returns an ordered list of values. If no arguments are given, returns
the ordered values of the entire hash. If a list of keys is given, returns
values in order corresponding to those keys. If a key does not exist, C<undef>
will be returned for that value.
In scalar context, returns the number of elements.
Current API available since 0.006.
=head2 get
$value = $oh->get("some key");
Returns the value associated with the key, or C<undef> if it does not exist in
the hash.
=head2 set
$oh->set("some key" => "some value");
Associates a value with a key and returns the value. If the key does not
already exist in the hash, it will be added at the end.
=head2 exists
if ( $oh->exists("some key") ) { ... }
Test if some key exists in the hash (without creating it).
=head2 delete
$value = $oh->delete("some key");
Removes a key-value pair from the hash and returns the value.
=head2 clear
$oh->clear;
Removes all key-value pairs from the hash. Returns undef in scalar context
or an empty list in list context.
Current API available since 0.003.
=head2 push
$oh->push( one => 1, two => 2);
Add a list of key-value pairs to the end of the ordered hash. If a key already
exists in the hash, it will be deleted and re-inserted at the end with the new
value.
Returns the number of keys after the push is complete.
=head2 pop
($key, $value) = $oh->pop;
$value = $oh->pop;
Removes and returns the last key-value pair in the ordered hash.
In scalar context, only the value is returned. If the hash is empty,
the returned key and value will be C<undef>.
=head2 unshift
$oh->unshift( one => 1, two => 2 );
Adds a list of key-value pairs to the beginning of the ordered hash. If a key
already exists, it will be deleted and re-inserted at the beginning with the
new value.
Returns the number of keys after the unshift is complete.
=head2 shift
($key, $value) = $oh->shift;
$value = $oh->shift;
Removes and returns the first key-value pair in the ordered hash.
In scalar context, only the value is returned. If the hash is empty,
the returned key and value will be C<undef>.
=head2 merge
$oh->merge( one => 1, two => 2 );
Merges a list of key-value pairs into the ordered hash. If a key already
exists, its value is replaced. Otherwise, the key-value pair is added at
the end of the hash.
=head2 as_list
@pairs = $oh->as_list;
@pairs = $oh->as_list( @keys );
Returns an ordered list of key-value pairs. If no arguments are given, all
pairs in the hash are returned. If a list of keys is given, the returned list
includes only those key-value pairs in the given order. Keys that aren't in
the original will have the value C<undef>.
=head2 iterator
$iter = $oh->iterator;
$iter = $oh->iterator( reverse $oh->keys ); # reverse
while ( my ($key,$value) = $iter->() ) { ... }
Returns a code reference that returns a single key-value pair (in order) on
each invocation, or the empty list if all keys are visited.
If no arguments are given, the iterator walks the entire hash in order. If a
list of keys is provided, the iterator walks the hash in that order. Unknown
keys will return C<undef>.
The list of keys to return is set when the iterator is generator. Keys added
later will not be returned. Subsequently deleted keys will return C<undef>
for the value.
=head2 preinc
$oh->preinc($key); # like ++$hash{$key}
This method is sugar for incrementing a key without having to call C<set> and
C<get> explicitly. It returns the new value.
Current API available since 0.005.
=head2 postinc
$oh->postinc($key); # like $hash{$key}++
This method is sugar for incrementing a key without having to call C<set> and
C<get> explicitly. It returns the old value.
Current API available since 0.005.
=head2 predec
$oh->predec($key); # like --$hash{$key}
This method is sugar for decrementing a key without having to call C<set> and
C<get> explicitly. It returns the new value.
Current API available since 0.005.
=head2 postdec
$oh->postdec($key); # like $hash{$key}--
This method is sugar for decrementing a key without having to call C<set> and
C<get> explicitly. It returns the old value.
Current API available since 0.005.
=head2 add
$oh->add($key, $n); # like $hash{$key} += $n
This method is sugar for adding a value to a key without having to call
C<set> and C<get> explicitly. With no value to add, it is treated as "0".
It returns the new value.
Current API available since 0.005.
=head2 subtract
$oh->subtract($key, $n); # like $hash{$key} -= $n
This method is sugar for subtracting a value from a key without having to call
C<set> and C<get> explicitly. With no value to subtract, it is treated as "0".
It returns the new value.
Current API available since 0.005.
=head2 concat
$oh->concat($key, $str); # like $hash{$key} .= $str
This method is sugar for concatenating a string onto the value of a key without
having to call C<set> and C<get> explicitly. It returns the new value. If the
value to append is not defined, no concatenation is done and no warning is
given.
Current API available since 0.005.
=head2 or_equals
$oh->or_equals($key, $str); # like $hash{$key} ||= $str
This method is sugar for assigning to a key if the existing value is false
without having to call C<set> and C<get> explicitly. It returns the new value.
Current API available since 0.005.
=head2 dor_equals
$oh->dor_equals($key, $str); # like $hash{$key} //= $str
This method is sugar for assigning to a key if the existing value is not
defined without having to call C<set> and C<get> explicitly. It returns the new
value.
Current API available since 0.005.
=head1 OVERLOADING
=head2 Boolean
if ( $oh ) { ... }
When used in boolean context, a Hash::Ordered object is true if it has any entries
and false otherwise.
=head2 String
say "$oh";
When used in string context, a Hash::Ordered object stringifies like typical
Perl objects. E.g. C<Hash::Ordered=ARRAY(0x7f815302cac0)>
Current API available since 0.005.
=head2 Numeric
$count = 0 + $oh;
When used in numeric context, a Hash::Ordered object numifies as the decimal
representation of its memory address, just like typical Perl objects. E.g.
C<140268162536552>
For the number of keys, call the L</keys> method in scalar context.
Current API available since 0.005.
=head2 Fallback
Other L<overload> methods are derived from these three, if possible.
=head1 TIED INTERFACE
Using C<tie> is slower than using method calls directly. But for
compatibility with libraries that can only take hashes, it's available if
you really need it:
tie my %hash, "Hash::Ordered", @pairs;
If you want to access the underlying object for method calls, use C<tied>:
tied( %hash )->unshift( @data );
Tied hash API available since 0.005.
=head1 CAVEATS
=head2 Deletion and order modification with push, pop, etc.
This can be expensive, as the ordered list of keys has to be updated. For
small hashes with no more than 25 keys, keys are found and spliced out with
linear search. As an optimization for larger hashes, the first change to the
ordered list of keys will construct an index to the list of keys. Thereafter,
removed keys will be marked with a "tombstone" record. Tombstones will be
garbage collected whenever the number of tombstones exceeds the number of valid
keys.
These internal implementation details largely shouldn't concern you. The
important things to note are:
=over 4
=item *
The costs of efficient deletion are deferred until you need it
=item *
Deleting lots of keys will temporarily appear to leak memory until garbage collection occurs
=back
=head1 MOTIVATION
For a long time, I used L<Tie::IxHash> for ordered hashes, but I grew
frustrated with things it lacked, like a cheap way to copy an IxHash object or
a convenient iterator when not using the tied interface. As I looked at its
implementation, it seemed more complex than I though it needed, with an extra
level of indirection that slows data access.
Given that frustration, I started experimenting with the simplest thing I
thought could work for an ordered hash: a hash of key-value pairs and an array
with key order.
As I worked on this, I also started searching for other modules doing similar
things. What I found fell broadly into two camps: modules based on tie (even
if they offered an OO interface), and pure OO modules. They all either lacked
features I deemed necessary or else seemed overly-complex in either
implementation or API.
Hash::Ordered attempts to find the sweet spot with simple implementation,
reasonably good efficiency for most common operations, and a rich, intuitive
API.
After discussions with Mario Roy about the potential use of Hash::Ordered
with L<MCE>, I optimized deletion of larger hashes and provided a tied
interface for compatibility. Mario's suggestions and feedback about
optimization were quite valuable. Thank you, Mario!
=head1 SEE ALSO
This section describes other ordered-hash modules I found on CPAN. For
benchmarking results, see L<Hash::Ordered::Benchmarks>.
=head2 Tie modules
The following modules offer some sort of tie interface. I don't like ties,
in general, because of the extra indirection involved over a direct method
call. Still, you can make any tied interface into a faster OO one with
C<tied>:
tied( %tied_hash )->FETCH($key);
L<Tie::Hash::Indexed> is implemented in XS and thus seems promising if
pure-Perl isn't a criterion; it generally fails tests on Perl 5.18 and
above due to the hash randomization change. Despite being XS, it is slower
than Hash::Ordered at everything exception creation and deletion.
L<Tie::IxHash> is probably the most well known and includes an OO API.
Given the performance problems it has, "well known" is the only real reason
to use it.
These other modules below have very specific designs/limitations and I
didn't find any of them suitable for general purpose use:
=over 4
=item *
L<Tie::Array::AsHash> — array elements split with separator; tie API only
=item *
L<Tie::Hash::Array> — ordered alphabetically; tie API only
=item *
L<Tie::InsertOrderHash> — ordered by insertion; tie API only
=item *
L<Tie::LLHash> — linked-list implementation; quite slow
=item *
L<Tie::StoredOrderHash> — ordered by last update; tie API only
=back
=head2 Other ordered hash modules
Other modules stick with an object-oriented API, with a wide variety of
implementation approaches.
L<Array::AsHash> is essentially an inverse implementation from
Hash::Ordered. It keeps pairs in an array and uses a hash to index into
the array. This indirection would already make hash-like operations
slower, but the specific implementation makes it even worse, with
abstractions and function calls that make getting or setting individual
items up to 10x slower than Hash::Ordered.
However, C<Array::AsHash> takes an arrayref to initialize, which is very
fast and can return the list of pairs faster, too. If you mostly create
and list out very large ordered hashes and very rarely touch individual
entries, I think this could be something to very cautiously consider.
These other modules below have restrictions or particularly complicated
implementations (often relying on C<tie>) and thus I didn't think any of
them really suitable for use:
=over 4
=item *
L<Array::Assign> — arrays with named access; restricted keys
=item *
L<Array::OrdHash> — overloads array/hash deref and uses internal tied data
=item *
L<Data::Pairs> — array of key-value hashrefs; allows duplicate keys
=item *
L<Data::OMap> — array of key-value hashrefs; no duplicate keys
=item *
L<Data::XHash> — blessed, tied hashref with doubly-linked-list
=back
=for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
=head1 SUPPORT
=head2 Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker
at L<https://github.com/dagolden/Hash-Ordered/issues>.
You will be notified automatically of any progress on your issue.
=head2 Source Code
This is open source software. The code repository is available for
public review and contribution under the terms of the license.
L<https://github.com/dagolden/Hash-Ordered>
git clone https://github.com/dagolden/Hash-Ordered.git
=head1 AUTHOR
David Golden <dagolden@cpan.org>
=head1 CONTRIBUTORS
=for stopwords Andy Lester Benct Philip Jonsson Mario Roy
=over 4
=item *
Andy Lester <andy@petdance.com>
=item *
Benct Philip Jonsson <bpjonsson@gmail.com>
=item *
Mario Roy <marioeroy@gmail.com>
=back
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2014 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
=cut
|