Var-Pairs-0.001003/000755 000765 000765 00000000000 12200736506 014300 5ustar00damiandamian000000 000000 Var-Pairs-0.001003/Changes000644 000765 000765 00000000764 12200736501 015575 0ustar00damiandamian000000 000000 Revision history for Var-Pairs 0.000001 Fri May 25 06:52:11 2012 Initial release. 0.001000 Wed Jul 18 13:54:16 2012 First public release 0.001001 Wed Jul 18 13:55:31 2012 Update README 0.001002 Sat Mar 23 07:58:28 2013 Removed autobox dependency for t/kvs.t (Thanks Salvatore!) 0.001003 Thu Aug 8 11:46:09 2013 Converted to use Devel::Callsite instead of Scope::Upper in order to identify caller location for the each_... family of functions. Var-Pairs-0.001003/lib/000755 000765 000765 00000000000 12200736506 015046 5ustar00damiandamian000000 000000 Var-Pairs-0.001003/Makefile.PL000644 000765 000765 00000001160 12200736067 016252 0ustar00damiandamian000000 000000 use strict; use warnings; use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Var::Pairs', AUTHOR => 'Damian Conway ', VERSION_FROM => 'lib/Var/Pairs.pm', ABSTRACT_FROM => 'lib/Var/Pairs.pm', PL_FILES => {}, LICENSE => 'perl', PREREQ_PM => { 'Test::More' => 0, 'Devel::Callsite' => 0.06, 'Data::Alias' => 1.16, 'PadWalker' => 1.93, }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'Var-Pairs-*' }, ); Var-Pairs-0.001003/MANIFEST000644 000765 000765 00000000557 12200736506 015440 0ustar00damiandamian000000 000000 Changes MANIFEST Makefile.PL README lib/Var/Pairs.pm t/00.load.t t/array.t t/array_while.t t/arrayref.t t/autobox.t t/coercions.t t/diagnostics.t t/hash.t t/hash_while.t t/hashref.t t/kv.t t/kvs.t t/lvalue.t t/nested.t t/nested_kv.t t/one_liner.t t/to_pair.t t/nexted_kv_same_statement.t META.yml Module meta-data (added by MakeMaker) Var-Pairs-0.001003/META.yml000644 000765 000765 00000001216 12200736506 015551 0ustar00damiandamian000000 000000 --- #YAML:1.0 name: Var-Pairs version: 0.001003 abstract: OO iterators and pair constructors for variables author: - Damian Conway license: perl distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: Data::Alias: 1.16 Devel::Callsite: 0.06 PadWalker: 1.93 Test::More: 0 no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.57_05 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 Var-Pairs-0.001003/README000644 000765 000765 00000001267 12200736501 015161 0ustar00damiandamian000000 000000 Var::Pairs version 0.001003 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. INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install Alternatively, to install with Module::Build, you can use the following commands: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES None. COPYRIGHT AND LICENCE Copyright (C) 2012, Damian Conway This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Var-Pairs-0.001003/t/000755 000765 000765 00000000000 12200736506 014543 5ustar00damiandamian000000 000000 Var-Pairs-0.001003/t/00.load.t000644 000765 000765 00000000167 11757521036 016077 0ustar00damiandamian000000 000000 use Test::More tests => 1; BEGIN { use_ok( 'Var::Pairs' ); } diag( "Testing Var::Pairs $Var::Pairs::VERSION" ); Var-Pairs-0.001003/t/array.t000644 000765 000765 00000000445 11757521065 016061 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 12; use Var::Pairs; my @data = 'a'..'f'; for my $next (pairs @data) { state $count = 0; ok $next->index == $count => 'index method correct'; ok $next->value eq $data[$count] => 'value method correct'; $count++; } Var-Pairs-0.001003/t/array_while.t000644 000765 000765 00000000611 11776401264 017243 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 13; use Var::Pairs; my @data = 'a'..'f'; while (my $next = each_pair @data) { state $count = 0; ok $next->index == $count => 'index method correct'; ok $next->value eq $data[$count] => 'value method correct'; $count++; END { ok $count == @data => 'correct number of iterations'; } } Var-Pairs-0.001003/t/arrayref.t000644 000765 000765 00000000471 11757521071 016552 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 12; use Var::Pairs; my $data_ref = ['a'..'f']; for my $next (pairs $data_ref) { state $count = 0; ok $next->index == $count => 'index method correct'; ok $next->value eq $data_ref->[$count] => 'value method correct'; $count++; } Var-Pairs-0.001003/t/autobox.t000644 000765 000765 00000001416 12200735661 016414 0ustar00damiandamian000000 000000 use 5.014; no if $] >= 5.018, warnings => "experimental::smartmatch"; use Test::More; plan eval { require autobox } ? (tests => 25) : (skip_all => 'This test requires autobox, which could not be loaded'); use Var::Pairs; my @data = 'a'..'f'; for my $next (@data->pairs) { state $count = 0; ok $next->index == $count => 'index method correct'; ok $next->value eq $data[$count] => 'value method correct'; $count++; } my $data_ref = {}; @{$data_ref}{1..6} = ('a'..'f'); while (my $next = $data_ref->each_pair) { ok $next->key ~~ $data_ref => 'key method correct'; ok $next->value eq $data_ref->{$next->key} => 'value method correct'; delete $data_ref->{$next->key}; } ok !keys $data_ref => 'Iterated all'; Var-Pairs-0.001003/t/coercions.t000644 000765 000765 00000001220 11757521075 016720 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 24; use Var::Pairs; my %data; @data{1..6} = ('a', 2, 'c', 4, 'e', 6); for my $next (pairs %data) { ok $next => 'Pair boolified as expected'; if ($next->key % 2) { is "$next", $next->key . ' => "' . $next->value . '"' => 'Stringified as expected'; } else { is "$next", $next->key . ' => ' . $next->value => 'Stringified as expected'; } ok !defined eval { 0 + $next } => 'Failed to numerify (as expected)'; like $@, qr/Can't convert Pair\(.*?\) to a number/ => 'Appropriate error message'; } Var-Pairs-0.001003/t/diagnostics.t000644 000765 000765 00000003426 11776226133 017253 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 6; use Var::Pairs; subtest 'pairs() expects hash or array' => sub { ok !eval{ my @pairs = pairs sub{} } => 'Failed when given bad ref'; like $@, qr/Argument to pairs\(\) must be array or hash \(not code\)/ => 'Correct error message'; }; subtest 'pairs expects a containers, not a scalar' => sub { ok !eval{ my @pairs = pairs 'string' } => 'Failed when given non-container'; like $@, qr/Argument to pairs\(\) must be array or hash \(not scalar value\)/ => 'Correct error message'; }; subtest "Pairs don't numerify when value is number" => sub { my @pairs = pairs { a=>1, b=>2, c=>3}; ok !eval{ 0 + $pairs[0] } => 'Failed when numerifying pair'; like $@, qr/Can't convert Pair\([abc] => [123]\) to a number/ => 'Correct error message'; }; subtest "Pairs don't numerify when value is string" => sub { my @pairs = pairs { a=>'x', b=>'y', c=>'z'}; ok !eval{ 0 + $pairs[0] } => 'Failed when numerifying pair'; like $@, qr/Can't convert Pair\([abc] => "[xyz]"\) to a number/ => 'Correct error message'; }; subtest "Pairs don't numerify when value is ref" => sub { my @pairs = pairs { a=>['x','y'], b=>['x','y'], c=>['x','y']}; ok !eval{ 0 + $pairs[0] } => 'Failed when numerifying pair'; like $@, qr/Can't convert Pair\([abc] => ARRAY\) to a number/ => 'Correct error message'; }; subtest "Can't call pairs in non-list contexts" => sub { my $pairs = eval{ pairs { a=>['x','y'], b=>['x','y'], c=>['x','y']} }; like $@, qr/Invalid call to pairs\(\) in scalar context/ => 'Correct error message in scalar context'; eval{ pairs [1..10] }; like $@, qr/Useless use of pairs\(\) in void context/ => 'Correct error message in void context'; }; Var-Pairs-0.001003/t/hash.t000644 000765 000765 00000000616 12200735652 015657 0ustar00damiandamian000000 000000 use 5.014; use strict; no if $] >= 5.018, warnings => "experimental::smartmatch"; use Test::More tests => 13; use Var::Pairs; my %data; @data{1..6} = ('a'..'f'); for my $next (pairs %data) { ok $next->key ~~ %data => 'key method correct'; ok $next->value eq $data{$next->key} => 'value method correct'; delete $data{$next->key}; } ok !keys %data => 'Iterated all'; Var-Pairs-0.001003/t/hash_while.t000644 000765 000765 00000000632 12200735665 017051 0ustar00damiandamian000000 000000 use 5.014; no if $] >= 5.018, warnings => "experimental::smartmatch"; use strict; use Test::More tests => 13; use Var::Pairs; my %data; @data{1..6} = ('a'..'f'); while (my $next = each_pair %data) { ok $next->key ~~ %data => 'key method correct'; ok $next->value eq $data{$next->key} => 'value method correct'; delete $data{$next->key}; } ok !keys %data => 'Iterated all'; Var-Pairs-0.001003/t/hashref.t000644 000765 000765 00000000725 12200735667 016363 0ustar00damiandamian000000 000000 use 5.014; no if $] >= 5.018, warnings => "experimental::smartmatch"; use strict; use Test::More tests => 13; use Var::Pairs; my $data_ref = {}; @{$data_ref}{1..6} = ('a'..'f'); my @keys = keys $data_ref; for my $next (pairs $data_ref) { ok $next->key ~~ $data_ref => 'key method correct'; ok $next->value eq $data_ref->{$next->key} => 'value method correct'; delete $data_ref->{$next->key}; } ok !keys $data_ref => 'Iterated all'; Var-Pairs-0.001003/t/kv.t000644 000765 000765 00000001630 11776217276 015367 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 5; use Var::Pairs; # What each data type is supposed to expand to... my $scalar = 'scalar value'; my $expected_scalar = [ 'scalar' => $scalar ]; my $ref = [-10..-1]; my $expected_ref = [ 'ref' => $ref ]; my @array = 1..10; my $expected_array = [ 'array' => \@array ]; my %hash; @hash{1..6} = ('a'..'f'); my $expected_hash = [ 'hash' => \%hash ]; # Do single args expand correctly??? is_deeply [to_kv($scalar)], $expected_scalar => 'to_kv $scalar'; is_deeply [to_kv($ref)], $expected_ref => 'to_kv $ref'; is_deeply [to_kv(@array)], $expected_array => 'to_kv @array'; is_deeply [to_kv(%hash)], $expected_hash => 'to_kv %hash'; # Do multiple args expand correctly??? is_deeply [to_kv $scalar, @array, %hash ], [@$expected_scalar, @$expected_array, @$expected_hash] => 'to_kv $scalar, @array, %hash'; Var-Pairs-0.001003/t/kvs.t000644 000765 000765 00000000542 12123250756 015536 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 12; use Var::Pairs; my @data = 'a'..'f'; my %data = kvs @data; for my $index (0..$#data) { is $data[$index], $data{$index} => "kv'd index $index correctly"; } while (1) { my ($index, $value) = each_kv @data or last; is $data[$index], $value => "each_kv'd index $index correctly"; } Var-Pairs-0.001003/t/lvalue.t000644 000765 000765 00000000607 11757521102 016223 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 2; use Var::Pairs; my @data = 'a'..'f'; for my $next (pairs @data) { $next->value = uc $next->value; } is_deeply \@data, ['A'..'F'] => 'Lvalue array ->value'; my %data; @data{1..6} = ('a'..'f'); for my $next (pairs %data) { $next->value .= 'z'; } is_deeply [sort values %data], [qw(az bz cz dz ez fz)] => 'Lvalue hash ->value'; Var-Pairs-0.001003/t/nested.t000644 000765 000765 00000000507 11776401322 016216 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 1; use Var::Pairs; my @data = 'a'..'f'; while (my $next_outer = each_pair @data) { while (my $next_inner = each_pair @data) { state $count = 0; $count++; END { ok $count == @data * @data => 'correct number of iterations'; } } } Var-Pairs-0.001003/t/nested_kv.t000644 000765 000765 00000000520 11776401330 016710 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 1; use Var::Pairs; my @data = 'a'..'f'; while (my ($next_outer) = each_kv @data) { while (my ($next_inner) = each_kv @data) { state $count = 0; $count++; END { cmp_ok $count, '==', @data * @data => "correct number of iterations"; } } } Var-Pairs-0.001003/t/nexted_kv_same_statement.t000644 000765 000765 00000000715 12200735522 022010 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More; use Var::Pairs; my @data = 'a'..'f'; plan tests => 1 + 2 * @data; my ($iter1, $iter2); while (my ($key1, $val1) = each_kv(@data) and my ($key2, $val2) = each_kv(@data)) { state $count = 0; $count++; is $key1, $key2 => "Iterated key in parallel ($key1)"; is $val1, $val2 => "Iterated value in parallel ($val1)"; END { cmp_ok $count, '==', @data => "correct number of iterations"; } } Var-Pairs-0.001003/t/one_liner.t000644 000765 000765 00000001465 12200736245 016710 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 3; use Var::Pairs; { my @results; my @data = 'a'..'f'; for my $next1 (pairs @data) { for my $next2 (pairs @data) { push @results, $next1->value . $next2->value; }} is_deeply \@results, [grep {/^[a-f][a-f]$/} 'aa'..'ff'] => 'nested one-liner'; } { my @results; my @data = 'a'..'f'; for my $next1 (pairs @data, pairs @data) { push @results, $next1->value; } is_deeply \@results, ['a'..'f','a'..'f'] => 'repeated pairs'; } { my @data = 'a'..'f'; while (my $next_outer = each_pair @data) { while (my $next_inner = each_pair @data) { state $count = 0; $count++; END { ok $count == @data * @data => 'correct number of iterations'; } }} } Var-Pairs-0.001003/t/to_pair.t000644 000765 000765 00000002253 11776221626 016400 0ustar00damiandamian000000 000000 use 5.014; use strict; use Test::More tests => 15; use Var::Pairs; # What each data type is supposed to expand to... my $scalar = 'scalar value'; my $ref = [-10..-1]; my @array = 1..10; my %hash; @hash{1..6} = ('a'..'f'); # Do single args expand correctly??? is +(to_pair($scalar))[0]->key, 'scalar' => 'to_pair $scalar key'; is +(to_pair($ref))[0]->key, 'ref' => 'to_pair $ref key'; is +(to_pair(@array))[0]->key, 'array' => 'to_pair @array key'; is +(to_pair(%hash))[0]->key, 'hash' => 'to_pair %hash key'; is +(to_pair($scalar))[0]->value, $scalar => 'to_pair $scalar value'; is +(to_pair($ref))[0]->value, $ref => 'to_pair $ref value'; is +(to_pair(@array))[0]->value, \@array => 'to_pair @array value'; is +(to_pair(%hash))[0]->value, \%hash => 'to_pair %hash value'; # Do multiple args expand correctly??? my @list = to_pair $scalar, @array, %hash; is scalar(@list), 3 => 'Correct number of args'; is $list[0]->key, 'scalar' => 'to_pair list keys'; is $list[1]->key, 'array'; is $list[2]->key, 'hash'; is $list[0]->value, $scalar => 'to_pair list values'; is $list[1]->value, \@array; is $list[2]->value, \%hash; Var-Pairs-0.001003/lib/Var/000755 000765 000765 00000000000 12200736506 015576 5ustar00damiandamian000000 000000 Var-Pairs-0.001003/lib/Var/Pairs.pm000644 000765 000765 00000055647 12200736501 017226 0ustar00damiandamian000000 000000 package Var::Pairs; our $VERSION = '0.001003'; use 5.014; use warnings; no if $] >= 5.018, warnings => "experimental::smartmatch"; use Carp; use Devel::Callsite; # Check for autoboxing, and set up pairs() method if applicable.. my $autoboxing; BEGIN { if (eval{ require autobox }) { $autoboxing = 1; push @Var::Pairs::ISA, 'autobox'; *Var::Pairs::autobox::pairs = \&Var::Pairs::pairs; *Var::Pairs::autobox::kvs = \&Var::Pairs::kvs; *Var::Pairs::autobox::each_pair = \&Var::Pairs::each_pair; *Var::Pairs::autobox::each_kv = \&Var::Pairs::each_kv; *Var::Pairs::autobox::invert = \&Var::Pairs::invert; *Var::Pairs::autobox::invert_pairs = \&Var::Pairs::invert_pairs; } } sub import { my ($class) = @_; # Export API... no strict 'refs'; my $caller = caller; for my $subname (qw< pairs kvs each_pair each_kv to_kv to_pair invert invert_pairs >) { no strict 'refs'; *{$caller.'::'.$subname} = \&{$subname}; } # Enable autoboxing of ->pairs() in caller's lexical scope, if possible... if ($autoboxing) { $class->SUPER::import( HASH => 'Var::Pairs::autobox', ARRAY => 'Var::Pairs::autobox', ); } } # Track iterators for each call... state %iterator_for; # Convert one or more vars into a ('varname', $varname,...) list... sub to_kv (\[$@%];\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]) { require PadWalker; # Grab caller vars... my ($lexvars, $packvars) = (PadWalker::peek_my(1), PadWalker::peek_our(1)); # Reverse them (creating addr --> name mapping) my %varname = (reverse(%$packvars), reverse(%$lexvars)); # Remove the name sigils... s/^.// for values %varname; # Take each var ref and convert to 'name' => 'ref_or_val' pairs... return map { $varname{$_} => (ref($_) =~ /SCALAR|REF/ ? $$_ : $_) } @_; } # Convert one or more vars into 'varname' => $varname pairs... sub to_pair (\[$@%];\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]\[$@%]) { require PadWalker; # Grab caller vars... my ($lexvars, $packvars) = (PadWalker::peek_my(1), PadWalker::peek_our(1)); # Reverse them (creating addr --> name mapping) my %varname = (reverse(%$packvars), reverse(%$lexvars)); # Remove the name sigils... s/^.// for values %varname; # Take each var ref and convert to 'name' => 'ref_or_val' pairs... return map { Var::Pairs::Pair->new($varname{$_} => (ref($_) =~ /SCALAR|REF/ ? $$_ : $_), 'none') } @_; } # Generate pairs for iterating hashes and arrays... sub pairs (+) { if (!defined wantarray) { croak("Useless use of pairs() in void context"); } elsif (!wantarray) { croak("Invalid call to pairs() in scalar context.\nDid you mean each_pair()?\nError") } my $container_ref = shift; my $container_type = ref $container_ref || 'scalar value'; # Verify the single argument... if ($container_type !~ m{^ARRAY$|^HASH$}) { croak "Argument to pairs() must be array or hash (not \L$container_type\E)"; } # Uniquely identify this call, according to its lexical context... my $ID = callsite(); # Short-circuit if this is a repeated call... if (!wantarray && $iterator_for{$ID}) { return _get_each_pair($ID); } # Generate the list of pairs, according to the container type... my $container_is_array = $container_type eq 'ARRAY'; my @pairs = map { Var::Pairs::Pair->new($_, $container_ref, $container_is_array ? 'array' : 'hash') } $container_is_array ? 0..$#{$container_ref} : keys $container_ref; # Return them all in list context... return @pairs; # In scalar context, return the first pair, remembering the rest... $iterator_for{$ID} = \@pairs; return shift @pairs; } sub each_pair (+) { my ($container_ref) = @_; # Uniquely identify this call, according to its lexical context... my $ID = callsite(); # Build an iterator... $iterator_for{$ID} //= [ &pairs ]; # Iterate... return _get_each_pair($ID); } # Generate key, value,... lists for iterating hashes and arrays... sub kvs (+) { if (!defined wantarray) { croak("Useless use of kvs() in void context"); } elsif (!wantarray) { croak("Invalid call to kvs() in scalar context.\nDid you mean each_kv()?\nError") } my $container_ref = shift; my $container_type = ref $container_ref || 'scalar value'; # Verify the single argument... if ($container_type !~ m{^ARRAY$|^HASH$}) { croak "Argument to pairs() must be array or hash (not \L$container_type\E)"; } # Uniquely identify this call, according to its lexical context... my $ID = callsite(); # Return the key/value list, according to the container type... if ($container_type eq 'ARRAY') { return map { ($_, $container_ref->[$_]) } 0..$#{$container_ref}; } else { return %{$container_ref}; } } sub each_kv (+) { my ($container_ref) = @_; # Uniquely identify this call, according to its lexical context... my $ID = callsite(); # Build an iterator... $iterator_for{$ID} //= [ &kvs ]; # Iterate... return _get_each_kv($ID); } # Invert the key=>values of a hash or array... sub invert (+) { goto &_invert; } sub invert_pairs (+) { push @_, 1; goto &_invert; } # Utilities... # Perform var inversions... sub _invert { my ($var_ref, $return_as_pairs) = @_; my %inversion; if (!defined wantarray) { croak 'Useless use of invert() in void context'; } elsif (!wantarray) { croak 'Invalid call to invert() in scalar context'; } given (ref($var_ref) || 'SCALAR') { when ('HASH') { for my $key (keys $var_ref) { my $values = $var_ref->{$key}; for my $value ( ref $values eq 'ARRAY' ? @$values : $values ) { $inversion{$value} //= []; push $inversion{$value}, $key; } } } when ('ARRAY') { for my $key (0..$#{$var_ref}) { my $values = $var_ref->[$key]; for my $value ( ref $values eq 'ARRAY' ? @$values : $values ) { $inversion{$value} //= []; push $inversion{$value}, $key; } } } default { croak "Argument to invert() must be hash or array (not \L$_\E)"; } } return $return_as_pairs ? pairs %inversion : %inversion; } # Iterate, cleaning up if appropriate... sub _get_each_pair { my $ID = shift; # Iterator the requested iterator... my $each_pair = shift $iterator_for{$ID}; # If nothing was left to iterate, clean up the empty iterator... if (!defined $each_pair) { delete $iterator_for{$ID}; } return $each_pair; } sub _get_each_kv { my $ID = shift; # Iterator the requested iterator... my @each_kv = splice $iterator_for{$ID}, 0, 2; # If nothing was left to iterate, clean up the empty iterator... if (!@each_kv) { delete $iterator_for{$ID}; } # Return key or key/value, as appropriate (a la each())... return wantarray ? @each_kv : $each_kv[0]; } # Class implementing each key/value pair... package Var::Pairs::Pair { use Hash::Util qw< fieldhash >; use Scalar::Util qw< looks_like_number >; use Data::Alias; use Carp; # Each pair object has two attributes... fieldhash my %key_for; fieldhash my %value_for; # Accessors for the attributes (value is read/write)... sub value :lvalue { $value_for{shift()} } sub index { $key_for{shift()} } sub key { $key_for{shift()} } # The usual inside-out constructor... sub new { my ($class, $key, $container_ref, $container_type) = @_; # Create a scalar based object... my $new_obj = bless \do{ my $scalar }, $class; # Initialize its attributes (value needs to be an alias to the original)... $key_for{$new_obj} = $key; alias $value_for{$new_obj} = $container_type eq 'array' ? $container_ref->[$key] : $container_type eq 'none' ? $_[2] : $container_ref->{$key}; return $new_obj; } # Type coercions... use overload ( # As a string, a pair is just: key => value q{""} => sub { my $self = shift; my $value = $value_for{$self}; $value = ref $value ? ref $value : looks_like_number($value) ? $value : qq{"$value"}; return "$key_for{$self} => $value"; }, # Can't numerify a pair (make it a hanging offence)... q{0+} => sub { croak "Can't convert Pair(".shift.") to a number" }, # All pairs are true (just as in Perl 6)... q{bool} => sub { 1 }, # Everything else as normal... fallback => 1, ); } 1; # Magic true value required at end of module __END__ =head1 NAME Var::Pairs - OO iterators and pair constructors for variables =head1 VERSION This document describes Var::Pairs version 0.001003 =head1 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; } # next_pair() iterates OO pairs from arrays and hashes... while (my $next = next_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; =head1 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. =head1 INTERFACE =head2 Array and hash iterators =over =item C =item C =item C In list context, C returns a list of "pair" objects, each of which contains one key/index and value from the argument. In scalar and void contexts, C 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 C function; specifically, a replacement that can be used in C loops. =back =over =item C =item C =item C In list context, C returns a list of alternating keys and values. That is C flattens the hash to C<(I, I, I, I...)> and C flattens the array to C<(I, I, I, I...)>. In scalar and void contexts, C 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; =back =over =item C =item C =item C In all contexts, C 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 C, so multiple calls to C on the same container variable can be nested without interacting with each other (i.e. unlike multiple calls to C). When the iterator is exhausted, the next call to C returns C 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 C in a C loop is the preferred idiom: for my $pair (pairs %container) { # ...do something with $pair->key and $pair->value } =back =over =item C =item C =item C In list contexts, C 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 C, a separate internal iterator is created for each call to C, so multiple calls to C on the same container variable can be nested without interacting with each other (i.e. unlike multiple calls to C). When the iterator is exhausted, the next call to C returns C 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, C is a drop-in replacement for Perl's built-in C, except that you can nest C iterations over the same variable without shooting yourself in the foot. =back =over =item C<< %hash->pairs >> =item C<< @array->pairs >> =item C<< $hash_or_array_ref->pairs >> =item C<< %hash->kvs >> =item C<< @array->kvs >> =item C<< $hash_or_array_ref->kvs >> =item C<< %hash->each_pair >> =item C<< @array->each_pair >> =item C<< $hash_or_array_ref->each_pair >> =item C<< %hash->each_kv >> =item C<< @array->each_kv >> =item C<< $hash_or_array_ref->each_kv >> If you have the C 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. =back =head2 Pairs =over =item C<< $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. =item C<< $pair->index >> Nothing but a synonym for C<< $pair->key >>. Use whichever suits your purpose, your program, or your predilections. =item C<< $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 C<%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 C<%items> hash whose key starts with 'Q'. =item C<< "$pair" >> When used as a string, a pair is converted to a suitable representation for a pair, namely: C<< "I => I" >> =item C<< if ($pair) {...} >> When a pair is used as a boolean, it is always true. =back =head2 Named pair constructors =over =item C<< to_pair $scalar, @array, %hash, $etc >> The C 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) ); =item C<< to_kv $scalar, @array, %hash, $etc >> The C subroutine takes one or more variables and converts each of them to a I C<< => >> I sequence (i.e. a two-element list, rather than a Pair object). As with C, 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}); =back =head2 Array and hash inverters =over =item C<< invert %hash >> =item C<< invert @array >> =item C<< invert $hash_or_array_ref >> The C 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'], ); C 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'], ); =item C<< invert_pairs %hash >> =item C<< invert_pairs @array >> =item C<< invert_pairs $hash_or_array_ref >> C acts exactly like C, except that it returns a list of Pair objects (like C does). This is not useful for initializing other hashes, but is handy for debugging a reverse mapping: say for invert_pairs %hash; =item C<< %hash->invert >> or C<< %hash->invert_pairs >> =item C<< @array->invert >> or C<< @array->invert_pairs >> =item C<< $hash_or_array_ref->invert >> or C<< $hash_or_array_ref->invert_pairs >> If you have the C 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. =back =head1 DIAGNOSTICS =over =item C<< Argument to %s must be hash or array (not %s) >> Except for C and C, 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. =item C<< Useless use of pairs() in void context >> =item C<< Useless use of kvs() in void context >> =item C<< 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. =item C<< Invalid call to pairs() in scalar context >> =item C<< Invalid call to kvs() in scalar context >> =item C<< 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 C or C is used in a C loop, instead of a C loop. Either change the type of loop, or else use C or C instead. =item C<< Can't convert Pair(%s => %s) to a number >> You attempted to use one of the pair objects returned by C as a number, but the module has no idea how to do that. You probably need to use C<< $pair->index >> or C<< $pair->value >> instead. =back =head1 CONFIGURATION AND ENVIRONMENT Var::Pairs requires no configuration files or environment variables. =head1 DEPENDENCIES The module requires Perl 5.014 and the following modules: =over =item Perl 5.14 or later =item Devel::Callsite =item Data::Alias =item PadWalker =back To use the optional C<< $container->pairs >> syntax, you also need the C module. =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to C, or through the web interface at L. =head1 ACKNOWLEDGEMENTS Based on a suggestion by Karl Brodowsky and inspired by several features of Perl 6. =head1 AUTHOR Damian Conway C<< >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2012, Damian Conway C<< >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 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.