Var::Pairs(3) OO iterators and pair constructors for variables

VERSION

This document describes Var::Pairs version 0.002004

SYNOPSIS


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;

DESCRIPTION

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.

INTERFACE

Array and hash iterators

"pairs %hash"
"pairs @array"
"pairs $hash_or_array_ref"
In list context, "pairs()" returns a list of ``pair'' objects, each of which contains one key/index and value from the argument. In scalar and void contexts, "pairs()" throws an exception.

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.

"kvs %hash"
"kvs @array"
"kvs $hash_or_array_ref"
In list context, "kvs()" returns a list of alternating keys and values. That is "kvs %hash" flattens the hash to "(key, value, key, value...)" and "kvs @array" flattens the array to "(index, value, index, value...)".

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;
"each_pair %hash"
"each_pair @array"
"each_pair $hash_or_array_ref"
In all contexts, "each_pair()" returns a single ``pair'' object, containing the key/index and value of the next element in the argument.

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 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
    }
"each_kv %hash"
"each_kv @array"
"each_kv $hash_or_array_ref"
In list contexts, "each_kv()" returns a list of two elements: the key/index and the value of the next element in the argument. In scalar contexts, just the next key is returned.

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 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.

"%hash->pairs"
"@array->pairs"
"$hash_or_array_ref->pairs"
"%hash->kvs"
"@array->kvs"
"$hash_or_array_ref->kvs"
"%hash->each_pair"
"@array->each_pair"
"$hash_or_array_ref->each_pair"
"%hash->each_kv"
"@array->each_kv"
"$hash_or_array_ref->each_kv"
If you have the "autobox" module installed, you can use this OO syntax as well. Apart from their call syntax, these OO forms are exactly the same as the subroutine-based interface described above.

Pairs

"$pair->key"
Returns a copy of the key of the pair, if the pair was derived from a hash. Returns a copy of the index of the pair, if the pair was derived from an array.
"$pair->index"
Nothing but a synonym for "$pair->key". Use whichever suits your purpose, your program, or your predilections.
"$pair->value"
Returns the value of the pair, as an lvalue. That is:

    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'.

"$pair->kv"
Returns a two-element list containing copies of the key and the value of the pair. That is:

    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.

"$pair"
When used as a string, a pair is converted to a suitable representation for a pair, namely: "key => value"
"0 + $pair"
Pairs cannot be used as numbers: an exception is thrown.
"if ($pair) {...}"
When a pair is used as a boolean, it is always true.

Named pair constructors

"to_pair $scalar, @array, %hash, $etc"
The "to_pair" subroutine takes one or more variables and converts each of them to a single Pair object. The Pair's 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_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)
    );
"to_kv $scalar, @array, %hash, $etc"
The "to_kv()" subroutine takes one or more variables and converts each of them to a key "=>" value sequence (i.e. a two-element list, rather than a Pair object).

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});

Array and hash inverters

"invert %hash"
"invert @array"
"invert $hash_or_array_ref"
The "invert" subroutine takes a single hash or array (or a reference to either) and returns a list of alternating keys and value, where each key is a value from the original variable and each corresponding value is a reference to an array containing the original key(s). This list is typically used to initialize a second hash, which can then be used as a reverse mapping. In other words:

    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'],
    );
"invert_pairs %hash"
"invert_pairs @array"
"invert_pairs $hash_or_array_ref"
"invert_pairs()" acts exactly like "invert()", except that it returns a list of Pair objects (like "pairs()" does).

This is not useful for initializing other hashes, but is handy for debugging a reverse mapping:

    say for invert_pairs %hash;
"%hash->invert" or "%hash->invert_pairs"
"@array->invert" or "@array->invert_pairs"
"$hash_or_array_ref->invert" or "$hash_or_array_ref->invert_pairs"
If you have the "autobox" module installed, you can use this OO syntax as well. Apart from their call syntax, these OO forms are exactly the same as the subroutine-based interfaces described above.

DIAGNOSTICS

"Argument to %s must be hash or array (not %s)"
Except for "to_pair()" and "to_kv()", all of the subroutines exported by this module only operate on hashes, arrays, or references to hashes or arrays. Asking for the ``pairs'' insidde a scalar, typeglob, or other entity is meaningless; they're simply not structured as collections of keyed values.
"Useless use of pairs() in void context"
"Useless use of kvs() in void context"
"Useless use of invert() in void context"
None of these subroutines has any side-effects, so calling them in void context is a waste of time.
"Invalid call to pairs() in scalar context"
"Invalid call to kvs() in scalar context"
"Invalid call to invert() in scalar context"
All these subroutines return a list, so in scalar context you just get a count (which there are cheaper and easier ways to obtain).

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.

"Can't convert Pair(%s => %s) to a number"
You attempted to use one of the pair objects returned by "pairs()" as a number, but the module has no idea how to do that.

You probably need to use "$pair->index" or "$pair->value" instead.

CONFIGURATION AND ENVIRONMENT

Var::Pairs requires no configuration files or environment variables.

DEPENDENCIES

The module requires Perl 5.014 and the following modules:
Perl 5.14 or later
Devel::Callsite
Data::Alias
PadWalker

To use the optional "$container->pairs" syntax, you also need the "autobox" module.

INCOMPATIBILITIES

None reported.

BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to "[email protected]", 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.

ACKNOWLEDGEMENTS

Based on a suggestion by Karl Brodowsky and inspired by several features of Perl 6.

AUTHOR

Damian Conway "<[email protected]>"

LICENCE AND COPYRIGHT

Copyright (c) 2012, Damian Conway "<[email protected]>". 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.

DISCLAIMER OF WARRANTY

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.