| Tie::Hash::MultiValueOrdered(3pm) | User Contributed Perl Documentation | Tie::Hash::MultiValueOrdered(3pm) |
Tie::Hash::MultiValueOrdered - hash with multiple values per key, and ordered keys
use Test::More;
use Tie::Hash::MultiValueOrdered;
my $tied = tie my %hash, "Tie::Hash::MultiValueOrdered";
$hash{a} = 1;
$hash{b} = 2;
$hash{a} = 3;
$hash{b} = 4;
# Order of keys is predictable
is_deeply(
[ keys %hash ],
[ qw( a b ) ],
);
# Order of values is predictable
# Note that the last values of 'a' and 'b' are returned.
is_deeply(
[ values %hash ],
[ qw( 3 4 ) ],
);
# Can retrieve list of all key-value pairs
is_deeply(
[ $tied->pairs ],
[ qw( a 1 b 2 a 3 b 4 ) ],
);
# Switch the retrieval mode for the hash.
$tied->fetch_first;
# Now the first values of 'a' and 'b' are returned.
is_deeply(
[ values %hash ],
[ qw( 1 2 ) ],
);
# Switch the retrieval mode for the hash.
$tied->fetch_list;
# Now arrayrefs are returned.
is_deeply(
[ values %hash ],
[ [1,3], [2,4] ],
);
# Restore the default retrieval mode for the hash.
$tied->fetch_last;
done_testing;
A hash tied to this class acts more or less like a standard hash, except that when you assign a new value to an existing key, the old value is retained underneath. An explicit "delete" deletes all values associated with a key.
By default, the old values are inaccessible through the hash interface, but can be retrieved via the tied object:
my @values = tied(%hash)->get($key);
However, the "fetch_*" methods provide a means to alter the behaviour of the hash.
tie my %hash, "Tie::Hash::MultiValueOrdered";
$hash{a} = 1;
$hash{b} = 2;
$hash{b} = 3;
tied(%hash)->fetch_last;
is($hash{a}, 1);
is($hash{b}, 3);
tie my %hash, "Tie::Hash::MultiValueOrdered";
$hash{a} = 1;
$hash{b} = 2;
$hash{b} = 3;
tied(%hash)->fetch_first;
is($hash{a}, 1);
is($hash{b}, 2);
tie my %hash, "Tie::Hash::MultiValueOrdered";
$hash{a} = 1;
$hash{b} = 2;
$hash{b} = 3;
tied(%hash)->fetch_first;
is_deeply($hash{a}, [1]);
is_deeply($hash{b}, [2, 3]);
tie my %hash, "Tie::Hash::MultiValueOrdered";
$hash{a} = 1;
$hash{b} = 2;
$hash{b} = 3;
tied(%hash)->fetch_iterator;
my $A = $hash{a};
my $B = $hash{b};
is($A->(), 1);
is($B->(), 2);
is($B->(), 3);
Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=JSON-MultiValueOrdered>.
JSON::Tiny::Subclassable, JSON::Tiny, Mojo::JSON.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2012-2013 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
| 2022-11-20 | perl v5.36.0 |