Var::Pairs(3pm) | User Contributed Perl Documentation | Var::Pairs(3pm) |
Var::Pairs - OO iterators and pair constructors for variables
This document describes Var::Pairs version 0.004001
use Var::Pairs; # pairs() lists all OO pairs from arrays and hashes... for my $next (pairs @array) { say $next->index, ' has the value ', $next->value; } # each_pair() iterates OO pairs from arrays and hashes... while (my $next = each_pair %hash) { say $next->key, ' had the value ', $next->value; $next->value++; } # to_kv() converts vars into var_name => var_value pairs... Sub::Install::install_sub({to_kv $code, $from, $into}); # invert() reverses a one-to-many mapping correctly... my %reverse_mapping = invert %mapping; my %reverse_lookup = invert @data;
This module exports a small number of subroutines that add some Perl 6 conveniences to Perl 5. Specifically, the module exports several subroutines that simplify interactions with key/value pairs in hashes and arrays.
The typical list usage is:
for my $pair (pairs %container) { # ...do something with $pair }
The intent is to provide a safe and reliable replacement for the built-in "each()" function; specifically, a replacement that can be used in "for" loops.
In scalar and void contexts, "kvs()" throws an exception.
The most typical use is to populate a hash from an array:
my %hash = kvs @array; # does the same as: my %hash; @hash{0..$#array} = @array;
A separate internal iterator is created for each call to "each_pair()", so multiple calls to "each_pair()" on the same container variable can be nested without interacting with each other (i.e. unlike multiple calls to "each()").
When the iterator is exhausted, the next call to "each_pair()" returns "undef" or an empty list (depending on context), and resets the iterator. The iterator is also reset when execution leaves the block in which "each_pair()" is called. This means, for example, that "last"-ing out of the middle of an iterated loop does the right thing (by resetting the iterator).
The typical usage is:
while (my $pair = each_pair %container) { # ...do something with $pair->key and $pair->value }
Note, however, that using "pairs()" in a "for" loop is the preferred idiom:
for my $pair (pairs %container) { # ...do something with $pair->key and $pair->value }
The "each_pair()" subroutine can also be passed a reference to a subroutine, in which case that subroutine is used directly as the iterator.
When iterated, this iterator subroutine is called in list context and is expected to return a single value on each call (i.e. the next value to be iterated), or else an empty list when the iterator is exhausted.
For example:
# Calling this sub returns a reference to an anonymous iterator sub... sub count_down { my ($from, $to) = @_; return sub { return () if $from < $to; # End of iterator return $from--; # Next iterated value } } # Build a 10-->1 countdown and iterate it... while (my $next = each_pair count_down(10, 1)) { say $next->value; }
As with "each_pair()", a separate internal iterator is created for each call to "each_kv()", so multiple calls to "each_kv()" on the same container variable can be nested without interacting with each other (i.e. unlike multiple calls to "each()").
When the iterator is exhausted, the next call to "each_kv()" returns "undef" in scalar context or an empty list in list context, and resets the iterator. The iterator is also reset when execution leaves the block in which "each_kv()" is called.
The typical list usage is:
while (my ($key1, $val1) = each_kv %container) { while (my ($key2, $val2) = each_kv %container) { # ...do something with the two keys and two values } }
The typical scalar usage is:
while (my $key1 = each_kv %container) { while (my $key2 = each_kv %container) { # ...do something with the two keys } }
In other words, "each_kv()" is a drop-in replacement for Perl's built-in "each()", with two exceptions: one an advantage, the other a limitation. The advantage is that you can nest "each_kv()" iterations over the same variable without shooting yourself in the foot. The limitation is that, unlike "each()", "each_kv()" does not reset when you call the "keys" function on the hash you're iterating.
For example:
# Build a 10-->1 countdown and iterate it... while (my ($next) = each_value count_down(10, -10)) { say $next; } while (my $value1 = each_value %container) { while (my $value2 = each_value %container) { # ...do something with the two values } }
Note that, if your iterator can return a false value, such as 0 from the "count_down()" iterator in the previous example, then you should call "each_value()" in list context (as in the "count_down()" example) so that the false value does not prematurely terminate the "while" loop.
for my $item (pairs %items) { say $item->value if $item->key =~ /\d/; }
will print the value of every entry in the %items hash whose key includes a digit.
And:
for my $item (pairs %items) { $item->value++; if $item->key =~ /^Q/; }
will increment each value in the %items hash whose key starts with 'Q'.
for my $item (pairs %items) { my ($k, $v) = $item->kv; say $v if $k =~ /\d/; }
will print the value of every entry in the %items hash whose key includes a digit.
That is:
to_pair $scalar, @array, %hash, $etc
is equivalent to:
Pair->new( scalar => $scalar ), Pair->new( array => \@array ), Pair->new( hash => \%hash ), Pair->new( etc => $etc )
This is especially useful for generating modern sets of named arguments for other subroutines. For example:
Sub::Install::install_sub(to_pair $code, $from, $into);
instead of:
Sub::Install::install_sub( Pair->new(code => $code), Pair->new(from => $from), Pair->new(into => $into) );
As with "to_pair()", the key is the name of the variable (minus its leading sigil), and the value is the value of the variable (if it's a scalar) or a reference to the variable (if it's an array or hash).
That is:
to_kv $scalar, @array, %hash, $etc
is equivalent to:
scalar => $scalar, array => \@array, hash => \%hash, etc => $etc
This is especially useful for generating traditional sets of named arguments for other subroutines. For example:
Sub::Install::install_sub({to_kv $code, $from, $into});
instead of:
Sub::Install::install_sub({code => $code, from => $from, into => $into});
my %hash = ( a => 1, b => 2, c => 1, d => 1, e => 2, f => 3 ); my %inversion = invert %hash;
is equivalent to:
my %inversion = ( 1 => ['a', 'c', 'd'], 2 => ['b', 'e'], 3 => ['f'], );
"invert" correctly handles the many-to-many case where some of the values in the original are array references. For example:
my %hash = ( a => [1,2], b => 2, c => [1,3], d => 1, e => [3,2], f => 3 ); my %inversion = invert %hash;
is equivalent to:
my %inversion = ( 1 => ['a', 'c', 'd'], 2 => ['a', 'b', 'e'], 3 => ['c', 'e', 'f'], );
This is not useful for initializing other hashes, but is handy for debugging a reverse mapping:
say for invert_pairs %hash;
The most common case where this error is reported is when "pairs()" or "kvs()" is used in a "while" loop, instead of a "for" loop. Either change the type of loop, or else use "each_pair()" or "each_kv()" instead.
You probably need to use "$pair->index" or "$pair->value" instead.
Var::Pairs requires no configuration files or environment variables.
The module requires Perl 5.014 and the following modules:
To use the optional "$container->pairs" syntax, you also need the "autobox" module.
None reported.
No bugs have been reported.
Please report any bugs or feature requests to "bug-var-pairs@rt.cpan.org", or through the web interface at <http://rt.cpan.org>.
"each_kv()" acts like a true one-time only iterator (in the OO sense), so there is no way to reset its iteration (i.e. the way that calling "keys()" on a hash or array, resets any "each()" that is iterating it). If you need to reset partially iterated hashes or arrays, you will need to use some other mechanism to do so.
Based on a suggestion by Karl Brodowsky and inspired by several features of Perl 6.
Damian Conway "<DCONWAY@CPAN.org>"
Copyright (c) 2012, Damian Conway "<DCONWAY@CPAN.org>". All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
2022-12-12 | perl v5.36.0 |