List-MoreUtils-0.33/0000755000175100017510000000000011616464406012673 5ustar adamadamList-MoreUtils-0.33/META.yml0000644000175100017510000000117711616464406014152 0ustar adamadam--- #YAML:1.0 name: List-MoreUtils version: 0.33 abstract: Provide the stuff missing in List::Util author: - Tassilo von Parseval license: perl distribution_type: module configure_requires: ExtUtils::CBuilder: 0.27 ExtUtils::MakeMaker: 6.52 build_requires: Test::More: 0.42 requires: perl: 5.00503 Test::More: 0.82 no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.56 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 List-MoreUtils-0.33/README0000644000175100017510000003632511616464330013560 0ustar adamadamNAME List::MoreUtils - Provide the stuff missing in List::Util SYNOPSIS use List::MoreUtils qw{ any all none notall true false firstidx first_index lastidx last_index insert_after insert_after_string apply indexes after after_incl before before_incl firstval first_value lastval last_value each_array each_arrayref pairwise natatime mesh zip uniq distinct minmax part }; DESCRIPTION List::MoreUtils provides some trivial but commonly needed functionality on lists which is not going to go into List::Util. All of the below functions are implementable in only a couple of lines of Perl code. Using the functions from this module however should give slightly better performance as everything is implemented in C. The pure-Perl implementation of these functions only serves as a fallback in case the C portions of this module couldn't be compiled on this machine. any BLOCK LIST Returns a true value if any item in LIST meets the criterion given through BLOCK. Sets $_ for each item in LIST in turn: print "At least one value undefined" if any { ! defined($_) } @list; Returns false otherwise, or if LIST is empty. all BLOCK LIST Returns a true value if all items in LIST meet the criterion given through BLOCK, or if LIST is empty. Sets $_ for each item in LIST in turn: print "All items defined" if all { defined($_) } @list; Returns false otherwise. none BLOCK LIST Logically the negation of "any". Returns a true value if no item in LIST meets the criterion given through BLOCK, or if LIST is empty. Sets $_ for each item in LIST in turn: print "No value defined" if none { defined($_) } @list; Returns false otherwise. notall BLOCK LIST Logically the negation of "all". Returns a true value if not all items in LIST meet the criterion given through BLOCK. Sets $_ for each item in LIST in turn: print "Not all values defined" if notall { defined($_) } @list; Returns false otherwise, or if LIST is empty. true BLOCK LIST Counts the number of elements in LIST for which the criterion in BLOCK is true. Sets $_ for each item in LIST in turn: printf "%i item(s) are defined", true { defined($_) } @list; false BLOCK LIST Counts the number of elements in LIST for which the criterion in BLOCK is false. Sets $_ for each item in LIST in turn: printf "%i item(s) are not defined", false { defined($_) } @list; firstidx BLOCK LIST first_index BLOCK LIST Returns the index of the first element in LIST for which the criterion in BLOCK is true. Sets $_ for each item in LIST in turn: my @list = (1, 4, 3, 2, 4, 6); printf "item with index %i in list is 4", firstidx { $_ == 4 } @list; __END__ item with index 1 in list is 4 Returns -1 if no such item could be found. "first_index" is an alias for "firstidx". lastidx BLOCK LIST last_index BLOCK LIST Returns the index of the last element in LIST for which the criterion in BLOCK is true. Sets $_ for each item in LIST in turn: my @list = (1, 4, 3, 2, 4, 6); printf "item with index %i in list is 4", lastidx { $_ == 4 } @list; __END__ item with index 4 in list is 4 Returns -1 if no such item could be found. "last_index" is an alias for "lastidx". insert_after BLOCK VALUE LIST Inserts VALUE after the first item in LIST for which the criterion in BLOCK is true. Sets $_ for each item in LIST in turn. my @list = qw/This is a list/; insert_after { $_ eq "a" } "longer" => @list; print "@list"; __END__ This is a longer list insert_after_string STRING VALUE LIST Inserts VALUE after the first item in LIST which is equal to STRING. my @list = qw/This is a list/; insert_after_string "a", "longer" => @list; print "@list"; __END__ This is a longer list apply BLOCK LIST Applies BLOCK to each item in LIST and returns a list of the values after BLOCK has been applied. In scalar context, the last element is returned. This function is similar to "map" but will not modify the elements of the input list: my @list = (1 .. 4); my @mult = apply { $_ *= 2 } @list; print "\@list = @list\n"; print "\@mult = @mult\n"; __END__ @list = 1 2 3 4 @mult = 2 4 6 8 Think of it as syntactic sugar for for (my @mult = @list) { $_ *= 2 } before BLOCK LIST Returns a list of values of LIST upto (and not including) the point where BLOCK returns a true value. Sets $_ for each element in LIST in turn. before_incl BLOCK LIST Same as "before" but also includes the element for which BLOCK is true. after BLOCK LIST Returns a list of the values of LIST after (and not including) the point where BLOCK returns a true value. Sets $_ for each element in LIST in turn. @x = after { $_ % 5 == 0 } (1..9); # returns 6, 7, 8, 9 after_incl BLOCK LIST Same as "after" but also inclues the element for which BLOCK is true. indexes BLOCK LIST Evaluates BLOCK for each element in LIST (assigned to $_) and returns a list of the indices of those elements for which BLOCK returned a true value. This is just like "grep" only that it returns indices instead of values: @x = indexes { $_ % 2 == 0 } (1..10); # returns 1, 3, 5, 7, 9 firstval BLOCK LIST first_value BLOCK LIST Returns the first element in LIST for which BLOCK evaluates to true. Each element of LIST is set to $_ in turn. Returns "undef" if no such element has been found. "first_val" is an alias for "firstval". lastval BLOCK LIST last_value BLOCK LIST Returns the last value in LIST for which BLOCK evaluates to true. Each element of LIST is set to $_ in turn. Returns "undef" if no such element has been found. "last_val" is an alias for "lastval". pairwise BLOCK ARRAY1 ARRAY2 Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and returns a new list consisting of BLOCK's return values. The two elements are set to $a and $b. Note that those two are aliases to the original value so changing them will modify the input arrays. @a = (1 .. 5); @b = (11 .. 15); @x = pairwise { $a + $b } @a, @b; # returns 12, 14, 16, 18, 20 # mesh with pairwise @a = qw/a b c/; @b = qw/1 2 3/; @x = pairwise { ($a, $b) } @a, @b; # returns a, 1, b, 2, c, 3 each_array ARRAY1 ARRAY2 ... Creates an array iterator to return the elements of the list of arrays ARRAY1, ARRAY2 throughout ARRAYn in turn. That is, the first time it is called, it returns the first element of each array. The next time, it returns the second elements. And so on, until all elements are exhausted. This is useful for looping over more than one array at once: my $ea = each_array(@a, @b, @c); while ( my ($a, $b, $c) = $ea->() ) { .... } The iterator returns the empty list when it reached the end of all arrays. If the iterator is passed an argument of '"index"', then it retuns the index of the last fetched set of values, as a scalar. each_arrayref LIST Like each_array, but the arguments are references to arrays, not the plain arrays. natatime EXPR, LIST Creates an array iterator, for looping over an array in chunks of $n items at a time. (n at a time, get it?). An example is probably a better explanation than I could give in words. Example: my @x = ('a' .. 'g'); my $it = natatime 3, @x; while (my @vals = $it->()) { print "@vals\n"; } This prints a b c d e f g mesh ARRAY1 ARRAY2 [ ARRAY3 ... ] zip ARRAY1 ARRAY2 [ ARRAY3 ... ] Returns a list consisting of the first elements of each array, then the second, then the third, etc, until all arrays are exhausted. Examples: @x = qw/a b c d/; @y = qw/1 2 3 4/; @z = mesh @x, @y; # returns a, 1, b, 2, c, 3, d, 4 @a = ('x'); @b = ('1', '2'); @c = qw/zip zap zot/; @d = mesh @a, @b, @c; # x, 1, zip, undef, 2, zap, undef, undef, zot "zip" is an alias for "mesh". uniq LIST distinct LIST Returns a new list by stripping duplicate values in LIST. The order of elements in the returned list is the same as in LIST. In scalar context, returns the number of unique elements in LIST. my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4 my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5 minmax LIST Calculates the minimum and maximum of LIST and returns a two element list with the first element being the minimum and the second the maximum. Returns the empty list if LIST was empty. The "minmax" algorithm differs from a naive iteration over the list where each element is compared to two values being the so far calculated min and max value in that it only requires 3n/2 - 2 comparisons. Thus it is the most efficient possible algorithm. However, the Perl implementation of it has some overhead simply due to the fact that there are more lines of Perl code involved. Therefore, LIST needs to be fairly big in order for "minmax" to win over a naive implementation. This limitation does not apply to the XS version. part BLOCK LIST Partitions LIST based on the return value of BLOCK which denotes into which partition the current value is put. Returns a list of the partitions thusly created. Each partition created is a reference to an array. my $i = 0; my @part = part { $i++ % 2 } 1 .. 8; # returns [1, 3, 5, 7], [2, 4, 6, 8] You can have a sparse list of partitions as well where non-set partitions will be undef: my @part = part { 2 } 1 .. 10; # returns undef, undef, [ 1 .. 10 ] Be careful with negative values, though: my @part = part { -1 } 1 .. 10; __END__ Modification of non-creatable array value attempted, subscript -1 ... Negative values are only ok when they refer to a partition previously created: my @idx = ( 0, 1, -1 ); my $i = 0; my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8] EXPORTS Nothing by default. To import all of this module's symbols, do the conventional use List::MoreUtils ':all'; It may make more sense though to only import the stuff your program actually needs: use List::MoreUtils qw{ any firstidx }; ENVIRONMENT When "LIST_MOREUTILS_PP" is set, the module will always use the pure-Perl implementation and not the XS one. This environment variable is really just there for the test-suite to force testing the Perl implementation, and possibly for reporting of bugs. I don't see any reason to use it in a production environment. BUGS There is a problem with a bug in 5.6.x perls. It is a syntax error to write things like: my @x = apply { s/foo/bar/ } qw{ foo bar baz }; It has to be written as either my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz'; or my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/; Perl 5.5.x and Perl 5.8.x don't suffer from this limitation. If you have a functionality that you could imagine being in this module, please drop me a line. This module's policy will be less strict than List::Util's when it comes to additions as it isn't a core module. When you report bugs, it would be nice if you could additionally give me the output of your program with the environment variable "LIST_MOREUTILS_PP" set to a true value. That way I know where to look for the problem (in XS, pure-Perl or possibly both). SUPPORT Bugs should always be submitted via the CPAN bug tracker. THANKS Credits go to a number of people: Steve Purkis for giving me namespace advice and James Keenan and Terrence Branno for their effort of keeping the CPAN tidier by making List::Utils obsolete. Brian McCauley suggested the inclusion of apply() and provided the pure-Perl implementation for it. Eric J. Roode asked me to add all functions from his module "List::MoreUtil" into this one. With minor modifications, the pure-Perl implementations of those are by him. The bunch of people who almost immediately pointed out the many problems with the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN testers). A particularly nasty memory leak was spotted by Thomas A. Lowery. Lars Thegler made me aware of problems with older Perl versions. Anno Siegel de-orphaned each_arrayref(). David Filmer made me aware of a problem in each_arrayref that could ultimately lead to a segfault. Ricardo Signes suggested the inclusion of part() and provided the Perl-implementation. Robin Huston kindly fixed a bug in perl's MULTICALL API to make the XS-implementation of part() work. TODO A pile of requests from other people is still pending further processing in my mailbox. This includes: * List::Util export pass-through Allow List::MoreUtils to pass-through the regular List::Util functions to end users only need to "use" the one module. * uniq_by(&@) Use code-reference to extract a key based on which the uniqueness is determined. Suggested by Aaron Crane. * delete_index * random_item * random_item_delete_index * list_diff_hash * list_diff_inboth * list_diff_infirst * list_diff_insecond These were all suggested by Dan Muey. * listify Always return a flat list when either a simple scalar value was passed or an array-reference. Suggested by Mark Summersault. SEE ALSO List::Util AUTHOR Adam Kennedy Tassilo von Parseval COPYRIGHT AND LICENSE Some parts copyright 2011 Aaron Crane. Copyright 2004 - 2010 by Tassilo von Parseval This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. List-MoreUtils-0.33/LICENSE0000644000175100017510000004737111616464330013710 0ustar adamadam Terms of Perl itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" ---------------------------------------------------------------------------- The General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. 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 PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ---------------------------------------------------------------------------- The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. 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. The End List-MoreUtils-0.33/Makefile.PL0000644000175100017510000001001211616464330014633 0ustar adamadamuse strict; BEGIN { require 5.00503; } use Config (); use ExtUtils::MakeMaker (); # Should we build the XS version? my $make_xs = undef; foreach ( @ARGV ) { /^-pm/ and $make_xs = 0; /^-xs/ and $make_xs = 1; } unless ( defined $make_xs ) { $make_xs = can_xs(); } WriteMakefile( NAME => 'List::MoreUtils', ABSTRACT => 'Provide the stuff missing in List::Util', VERSION_FROM => 'lib/List/MoreUtils.pm', AUTHOR => 'Tassilo von Parseval ', LICENSE => 'perl', MIN_PERL_VERSION => '5.00503', CONFIGURE_REQUIRES => { 'ExtUtils::MakeMaker' => '6.52', 'ExtUtils::CBuilder' => '0.27', }, BUILD_REQUIRES => { 'Test::More' => '0.42', }, PREREQ_PM => { 'Test::More' => '0.82', }, # Special stuff CONFIGURE => sub { my $hash = $_[1]; unless ( $make_xs ) { $hash->{XS} = { }; $hash->{C} = [ ]; } return $hash; }, # Otherwise 'cxinc' isn't defined DEFINE => '-DPERL_EXT', ); ###################################################################### # Support Functions # Modified from eumm-upgrade by Alexandr Ciornii. sub WriteMakefile { my %params=@_; my $eumm_version=$ExtUtils::MakeMaker::VERSION; $eumm_version=eval $eumm_version; die "EXTRA_META is deprecated" if exists $params{EXTRA_META}; die "License not specified" unless exists $params{LICENSE}; if ( $params{BUILD_REQUIRES} and $eumm_version < 6.5503 ) { #EUMM 6.5502 has problems with BUILD_REQUIRES $params{PREREQ_PM}={ %{$params{PREREQ_PM} || {}} , %{$params{BUILD_REQUIRES}} }; delete $params{BUILD_REQUIRES}; } delete $params{CONFIGURE_REQUIRES} if $eumm_version < 6.52; delete $params{MIN_PERL_VERSION} if $eumm_version < 6.48; delete $params{META_MERGE} if $eumm_version < 6.46; delete $params{META_ADD} if $eumm_version < 6.46; delete $params{LICENSE} if $eumm_version < 6.31; delete $params{AUTHOR} if $] < 5.005; delete $params{ABSTRACT_FROM} if $] < 5.005; delete $params{BINARY_LOCATION} if $] < 5.005; ExtUtils::MakeMaker::WriteMakefile(%params); } # Secondary compile testing via ExtUtils::CBuilder sub can_xs { # Do we have the configure_requires checker? local $@; eval "require ExtUtils::CBuilder;"; if ( $@ ) { # They don't obey configure_requires, so it is # someone old and delicate. Try to avoid hurting # them by falling back to an older simpler test. return can_cc(); } # Do a simple compile that consumes the headers we need my @libs = (); my $object = undef; my $builder = ExtUtils::CBuilder->new( quiet => 1 ); unless ( $builder->have_compiler ) { # Lack of a compiler at all return 0; } eval { $object = $builder->compile( source => 'sanexs.c', ); @libs = $builder->link( objects => $object, module_name => 'sanexs', ); }; my $broken = !! $@; foreach ( $object, @libs ) { next unless defined $_; 1 while unlink $_; } if ( $broken ) { ### NOTE: Don't do this in a production release. # Compiler is officially screwed, you don't deserve # to do any of our downstream depedencies as you'll # probably end up choking on them as well. # Trigger an NA for their own protection. print "Unresolvable broken external dependency.\n"; print "This package requires a C compiler with full perl headers.\n"; print "Trivial test code using them failed to compile.\n"; print STDERR "NA: Unable to build distribution on this platform.\n"; exit(0); } return 1; } sub can_cc { my @chunks = split(/ /, $Config::Config{cc}) or return; # $Config{cc} may contain args; try to find out the program part while ( @chunks ) { return can_run("@chunks") || (pop(@chunks), next); } return; } sub can_run { my ($cmd) = @_; my $_cmd = $cmd; if ( -x $_cmd or $_cmd = MM->maybe_command($_cmd) ) { return $_cmd; } foreach my $dir ( (split /$Config::Config{path_sep}/, $ENV{PATH}), '.' ) { next if $dir eq ''; my $abs = File::Spec->catfile($dir, $cmd); return $abs if (-x $abs or $abs = MM->maybe_command($abs)); } return; } List-MoreUtils-0.33/xt/0000755000175100017510000000000011616464406013326 5ustar adamadamList-MoreUtils-0.33/xt/pmv.t0000644000175100017510000000125211616464330014311 0ustar adamadam#!/usr/bin/perl # Test that our declared minimum Perl version matches our syntax use strict; BEGIN { $| = 1; $^W = 1; } my @MODULES = ( 'Perl::MinimumVersion 1.27', 'Test::MinimumVersion 0.101080', ); # Don't run tests for installs use Test::More; unless ( $ENV{AUTOMATED_TESTING} or $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } # Load the testing modules foreach my $MODULE ( @MODULES ) { eval "use $MODULE"; if ( $@ ) { $ENV{RELEASE_TESTING} ? die( "Failed to load required release-testing module $MODULE" ) : plan( skip_all => "$MODULE not available for testing" ); } } all_minimum_version_from_metayml_ok(); List-MoreUtils-0.33/xt/meta.t0000644000175100017510000000107311616464330014436 0ustar adamadam#!/usr/bin/perl # Test that our META.yml file matches the current specification. use strict; BEGIN { $| = 1; $^W = 1; } my $MODULE = 'Test::CPAN::Meta 0.17'; # Don't run tests for installs use Test::More; unless ( $ENV{AUTOMATED_TESTING} or $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } # Load the testing module eval "use $MODULE"; if ( $@ ) { $ENV{RELEASE_TESTING} ? die( "Failed to load required release-testing module $MODULE" ) : plan( skip_all => "$MODULE not available for testing" ); } meta_yaml_ok(); List-MoreUtils-0.33/xt/pod.t0000644000175100017510000000116711616464330014276 0ustar adamadam#!/usr/bin/perl # Test that the syntax of our POD documentation is valid use strict; BEGIN { $| = 1; $^W = 1; } my @MODULES = ( 'Pod::Simple 3.14', 'Test::Pod 1.44', ); # Don't run tests for installs use Test::More; unless ( $ENV{AUTOMATED_TESTING} or $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } # Load the testing modules foreach my $MODULE ( @MODULES ) { eval "use $MODULE"; if ( $@ ) { $ENV{RELEASE_TESTING} ? die( "Failed to load required release-testing module $MODULE" ) : plan( skip_all => "$MODULE not available for testing" ); } } all_pod_files_ok(); List-MoreUtils-0.33/lib/0000755000175100017510000000000011616464406013441 5ustar adamadamList-MoreUtils-0.33/lib/List/0000755000175100017510000000000011616464406014354 5ustar adamadamList-MoreUtils-0.33/lib/List/MoreUtils.pm0000644000175100017510000005224511616464330016641 0ustar adamadampackage List::MoreUtils; use 5.00503; use strict; use Exporter (); use DynaLoader (); use vars qw{ $VERSION @ISA @EXPORT_OK %EXPORT_TAGS }; BEGIN { $VERSION = '0.33'; # $VERSION = eval $VERSION; @ISA = qw{ Exporter DynaLoader }; @EXPORT_OK = qw{ any all none notall true false firstidx first_index lastidx last_index insert_after insert_after_string apply indexes after after_incl before before_incl firstval first_value lastval last_value each_array each_arrayref pairwise natatime mesh zip uniq distinct minmax part }; %EXPORT_TAGS = ( all => \@EXPORT_OK, ); # Load the XS at compile-time so that redefinition warnings will be # thrown correctly if the XS versions of part or indexes loaded eval { # PERL_DL_NONLAZY must be false, or any errors in loading will just # cause the perl code to be tested local $ENV{PERL_DL_NONLAZY} = 0 if $ENV{PERL_DL_NONLAZY}; bootstrap List::MoreUtils $VERSION; 1; } unless $ENV{LIST_MOREUTILS_PP}; } eval <<'END_PERL' unless defined &any; # Use pure scalar boolean return values for compatibility with XS use constant YES => ! 0; use constant NO => ! 1; sub any (&@) { my $f = shift; foreach ( @_ ) { return YES if $f->(); } return NO; } sub all (&@) { my $f = shift; foreach ( @_ ) { return NO unless $f->(); } return YES; } sub none (&@) { my $f = shift; foreach ( @_ ) { return NO if $f->(); } return YES; } sub notall (&@) { my $f = shift; foreach ( @_ ) { return YES unless $f->(); } return NO; } sub true (&@) { my $f = shift; my $count = 0; foreach ( @_ ) { $count++ if $f->(); } return $count; } sub false (&@) { my $f = shift; my $count = 0; foreach ( @_ ) { $count++ unless $f->(); } return $count; } sub firstidx (&@) { my $f = shift; foreach my $i ( 0 .. $#_ ) { local *_ = \$_[$i]; return $i if $f->(); } return -1; } sub lastidx (&@) { my $f = shift; foreach my $i ( reverse 0 .. $#_ ) { local *_ = \$_[$i]; return $i if $f->(); } return -1; } sub insert_after (&$\@) { my ($f, $val, $list) = @_; my $c = -1; local *_; foreach my $i ( 0 .. $#$list ) { $_ = $list->[$i]; $c = $i, last if $f->(); } @$list = ( @{$list}[ 0 .. $c ], $val, @{$list}[ $c + 1 .. $#$list ], ) and return 1 if $c != -1; return 0; } sub insert_after_string ($$\@) { my ($string, $val, $list) = @_; my $c = -1; foreach my $i ( 0 .. $#$list ) { local $^W = 0; $c = $i, last if $string eq $list->[$i]; } @$list = ( @{$list}[ 0 .. $c ], $val, @{$list}[ $c + 1 .. $#$list ], ) and return 1 if $c != -1; return 0; } sub apply (&@) { my $action = shift; &$action foreach my @values = @_; wantarray ? @values : $values[-1]; } sub after (&@) { my $test = shift; my $started; my $lag; grep $started ||= do { my $x = $lag; $lag = $test->(); $x }, @_; } sub after_incl (&@) { my $test = shift; my $started; grep $started ||= $test->(), @_; } sub before (&@) { my $test = shift; my $more = 1; grep $more &&= ! $test->(), @_; } sub before_incl (&@) { my $test = shift; my $more = 1; my $lag = 1; grep $more &&= do { my $x = $lag; $lag = ! $test->(); $x }, @_; } sub indexes (&@) { my $test = shift; grep { local *_ = \$_[$_]; $test->() } 0 .. $#_; } sub lastval (&@) { my $test = shift; my $ix; for ( $ix = $#_; $ix >= 0; $ix-- ) { local *_ = \$_[$ix]; my $testval = $test->(); # Simulate $_ as alias $_[$ix] = $_; return $_ if $testval; } return undef; } sub firstval (&@) { my $test = shift; foreach ( @_ ) { return $_ if $test->(); } return undef; } sub pairwise (&\@\@) { my $op = shift; # Symbols for caller's input arrays use vars qw{ @A @B }; local ( *A, *B ) = @_; # Localise $a, $b my ( $caller_a, $caller_b ) = do { my $pkg = caller(); no strict 'refs'; \*{$pkg.'::a'}, \*{$pkg.'::b'}; }; # Loop iteration limit my $limit = $#A > $#B? $#A : $#B; # This map expression is also the return value local( *$caller_a, *$caller_b ); map { # Assign to $a, $b as refs to caller's array elements ( *$caller_a, *$caller_b ) = \( $A[$_], $B[$_] ); # Perform the transformation $op->(); } 0 .. $limit; } sub each_array (\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { return each_arrayref(@_); } sub each_arrayref { my @list = @_; # The list of references to the arrays my $index = 0; # Which one the caller will get next my $max = 0; # Number of elements in longest array # Get the length of the longest input array foreach ( @list ) { unless ( ref $_ eq 'ARRAY' ) { require Carp; Carp::croak("each_arrayref: argument is not an array reference\n"); } $max = @$_ if @$_ > $max; } # Return the iterator as a closure wrt the above variables. return sub { if ( @_ ) { my $method = shift; unless ( $method eq 'index' ) { require Carp; Carp::croak("each_array: unknown argument '$method' passed to iterator."); } # Return current (last fetched) index return undef if $index == 0 || $index > $max; return $index - 1; } # No more elements to return return if $index >= $max; my $i = $index++; # Return ith elements return map $_->[$i], @list; } } sub natatime ($@) { my $n = shift; my @list = @_; return sub { return splice @list, 0, $n; } } sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { my $max = -1; $max < $#$_ && ( $max = $#$_ ) foreach @_; map { my $ix = $_; map $_->[$ix], @_; } 0 .. $max; } sub uniq (@) { my %seen = (); grep { not $seen{$_}++ } @_; } sub minmax (@) { return unless @_; my $min = my $max = $_[0]; for ( my $i = 1; $i < @_; $i += 2 ) { if ( $_[$i-1] <= $_[$i] ) { $min = $_[$i-1] if $min > $_[$i-1]; $max = $_[$i] if $max < $_[$i]; } else { $min = $_[$i] if $min > $_[$i]; $max = $_[$i-1] if $max < $_[$i-1]; } } if ( @_ & 1 ) { my $i = $#_; if ($_[$i-1] <= $_[$i]) { $min = $_[$i-1] if $min > $_[$i-1]; $max = $_[$i] if $max < $_[$i]; } else { $min = $_[$i] if $min > $_[$i]; $max = $_[$i-1] if $max < $_[$i-1]; } } return ($min, $max); } sub part (&@) { my ($code, @list) = @_; my @parts; push @{ $parts[ $code->($_) ] }, $_ foreach @list; return @parts; } sub _XScompiled { return 0; } END_PERL die $@ if $@; # Function aliases *first_index = \&firstidx; *last_index = \&lastidx; *first_value = \&firstval; *last_value = \&lastval; *zip = \&mesh; *distinct = \&uniq; 1; __END__ =pod =head1 NAME List::MoreUtils - Provide the stuff missing in List::Util =head1 SYNOPSIS use List::MoreUtils qw{ any all none notall true false firstidx first_index lastidx last_index insert_after insert_after_string apply indexes after after_incl before before_incl firstval first_value lastval last_value each_array each_arrayref pairwise natatime mesh zip uniq distinct minmax part }; =head1 DESCRIPTION B provides some trivial but commonly needed functionality on lists which is not going to go into L. All of the below functions are implementable in only a couple of lines of Perl code. Using the functions from this module however should give slightly better performance as everything is implemented in C. The pure-Perl implementation of these functions only serves as a fallback in case the C portions of this module couldn't be compiled on this machine. =over 4 =item any BLOCK LIST Returns a true value if any item in LIST meets the criterion given through BLOCK. Sets C<$_> for each item in LIST in turn: print "At least one value undefined" if any { ! defined($_) } @list; Returns false otherwise, or if LIST is empty. =item all BLOCK LIST Returns a true value if all items in LIST meet the criterion given through BLOCK, or if LIST is empty. Sets C<$_> for each item in LIST in turn: print "All items defined" if all { defined($_) } @list; Returns false otherwise. =item none BLOCK LIST Logically the negation of C. Returns a true value if no item in LIST meets the criterion given through BLOCK, or if LIST is empty. Sets C<$_> for each item in LIST in turn: print "No value defined" if none { defined($_) } @list; Returns false otherwise. =item notall BLOCK LIST Logically the negation of C. Returns a true value if not all items in LIST meet the criterion given through BLOCK. Sets C<$_> for each item in LIST in turn: print "Not all values defined" if notall { defined($_) } @list; Returns false otherwise, or if LIST is empty. =item true BLOCK LIST Counts the number of elements in LIST for which the criterion in BLOCK is true. Sets C<$_> for each item in LIST in turn: printf "%i item(s) are defined", true { defined($_) } @list; =item false BLOCK LIST Counts the number of elements in LIST for which the criterion in BLOCK is false. Sets C<$_> for each item in LIST in turn: printf "%i item(s) are not defined", false { defined($_) } @list; =item firstidx BLOCK LIST =item first_index BLOCK LIST Returns the index of the first element in LIST for which the criterion in BLOCK is true. Sets C<$_> for each item in LIST in turn: my @list = (1, 4, 3, 2, 4, 6); printf "item with index %i in list is 4", firstidx { $_ == 4 } @list; __END__ item with index 1 in list is 4 Returns C<-1> if no such item could be found. C is an alias for C. =item lastidx BLOCK LIST =item last_index BLOCK LIST Returns the index of the last element in LIST for which the criterion in BLOCK is true. Sets C<$_> for each item in LIST in turn: my @list = (1, 4, 3, 2, 4, 6); printf "item with index %i in list is 4", lastidx { $_ == 4 } @list; __END__ item with index 4 in list is 4 Returns C<-1> if no such item could be found. C is an alias for C. =item insert_after BLOCK VALUE LIST Inserts VALUE after the first item in LIST for which the criterion in BLOCK is true. Sets C<$_> for each item in LIST in turn. my @list = qw/This is a list/; insert_after { $_ eq "a" } "longer" => @list; print "@list"; __END__ This is a longer list =item insert_after_string STRING VALUE LIST Inserts VALUE after the first item in LIST which is equal to STRING. my @list = qw/This is a list/; insert_after_string "a", "longer" => @list; print "@list"; __END__ This is a longer list =item apply BLOCK LIST Applies BLOCK to each item in LIST and returns a list of the values after BLOCK has been applied. In scalar context, the last element is returned. This function is similar to C but will not modify the elements of the input list: my @list = (1 .. 4); my @mult = apply { $_ *= 2 } @list; print "\@list = @list\n"; print "\@mult = @mult\n"; __END__ @list = 1 2 3 4 @mult = 2 4 6 8 Think of it as syntactic sugar for for (my @mult = @list) { $_ *= 2 } =item before BLOCK LIST Returns a list of values of LIST upto (and not including) the point where BLOCK returns a true value. Sets C<$_> for each element in LIST in turn. =item before_incl BLOCK LIST Same as C but also includes the element for which BLOCK is true. =item after BLOCK LIST Returns a list of the values of LIST after (and not including) the point where BLOCK returns a true value. Sets C<$_> for each element in LIST in turn. @x = after { $_ % 5 == 0 } (1..9); # returns 6, 7, 8, 9 =item after_incl BLOCK LIST Same as C but also inclues the element for which BLOCK is true. =item indexes BLOCK LIST Evaluates BLOCK for each element in LIST (assigned to C<$_>) and returns a list of the indices of those elements for which BLOCK returned a true value. This is just like C only that it returns indices instead of values: @x = indexes { $_ % 2 == 0 } (1..10); # returns 1, 3, 5, 7, 9 =item firstval BLOCK LIST =item first_value BLOCK LIST Returns the first element in LIST for which BLOCK evaluates to true. Each element of LIST is set to C<$_> in turn. Returns C if no such element has been found. C is an alias for C. =item lastval BLOCK LIST =item last_value BLOCK LIST Returns the last value in LIST for which BLOCK evaluates to true. Each element of LIST is set to C<$_> in turn. Returns C if no such element has been found. C is an alias for C. =item pairwise BLOCK ARRAY1 ARRAY2 Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and returns a new list consisting of BLOCK's return values. The two elements are set to C<$a> and C<$b>. Note that those two are aliases to the original value so changing them will modify the input arrays. @a = (1 .. 5); @b = (11 .. 15); @x = pairwise { $a + $b } @a, @b; # returns 12, 14, 16, 18, 20 # mesh with pairwise @a = qw/a b c/; @b = qw/1 2 3/; @x = pairwise { ($a, $b) } @a, @b; # returns a, 1, b, 2, c, 3 =item each_array ARRAY1 ARRAY2 ... Creates an array iterator to return the elements of the list of arrays ARRAY1, ARRAY2 throughout ARRAYn in turn. That is, the first time it is called, it returns the first element of each array. The next time, it returns the second elements. And so on, until all elements are exhausted. This is useful for looping over more than one array at once: my $ea = each_array(@a, @b, @c); while ( my ($a, $b, $c) = $ea->() ) { .... } The iterator returns the empty list when it reached the end of all arrays. If the iterator is passed an argument of 'C', then it retuns the index of the last fetched set of values, as a scalar. =item each_arrayref LIST Like each_array, but the arguments are references to arrays, not the plain arrays. =item natatime EXPR, LIST Creates an array iterator, for looping over an array in chunks of C<$n> items at a time. (n at a time, get it?). An example is probably a better explanation than I could give in words. Example: my @x = ('a' .. 'g'); my $it = natatime 3, @x; while (my @vals = $it->()) { print "@vals\n"; } This prints a b c d e f g =item mesh ARRAY1 ARRAY2 [ ARRAY3 ... ] =item zip ARRAY1 ARRAY2 [ ARRAY3 ... ] Returns a list consisting of the first elements of each array, then the second, then the third, etc, until all arrays are exhausted. Examples: @x = qw/a b c d/; @y = qw/1 2 3 4/; @z = mesh @x, @y; # returns a, 1, b, 2, c, 3, d, 4 @a = ('x'); @b = ('1', '2'); @c = qw/zip zap zot/; @d = mesh @a, @b, @c; # x, 1, zip, undef, 2, zap, undef, undef, zot C is an alias for C. =item uniq LIST =item distinct LIST Returns a new list by stripping duplicate values in LIST. The order of elements in the returned list is the same as in LIST. In scalar context, returns the number of unique elements in LIST. my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4 my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5 =item minmax LIST Calculates the minimum and maximum of LIST and returns a two element list with the first element being the minimum and the second the maximum. Returns the empty list if LIST was empty. The C algorithm differs from a naive iteration over the list where each element is compared to two values being the so far calculated min and max value in that it only requires 3n/2 - 2 comparisons. Thus it is the most efficient possible algorithm. However, the Perl implementation of it has some overhead simply due to the fact that there are more lines of Perl code involved. Therefore, LIST needs to be fairly big in order for C to win over a naive implementation. This limitation does not apply to the XS version. =item part BLOCK LIST Partitions LIST based on the return value of BLOCK which denotes into which partition the current value is put. Returns a list of the partitions thusly created. Each partition created is a reference to an array. my $i = 0; my @part = part { $i++ % 2 } 1 .. 8; # returns [1, 3, 5, 7], [2, 4, 6, 8] You can have a sparse list of partitions as well where non-set partitions will be undef: my @part = part { 2 } 1 .. 10; # returns undef, undef, [ 1 .. 10 ] Be careful with negative values, though: my @part = part { -1 } 1 .. 10; __END__ Modification of non-creatable array value attempted, subscript -1 ... Negative values are only ok when they refer to a partition previously created: my @idx = ( 0, 1, -1 ); my $i = 0; my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8] =back =head1 EXPORTS Nothing by default. To import all of this module's symbols, do the conventional use List::MoreUtils ':all'; It may make more sense though to only import the stuff your program actually needs: use List::MoreUtils qw{ any firstidx }; =head1 ENVIRONMENT When C is set, the module will always use the pure-Perl implementation and not the XS one. This environment variable is really just there for the test-suite to force testing the Perl implementation, and possibly for reporting of bugs. I don't see any reason to use it in a production environment. =head1 BUGS There is a problem with a bug in 5.6.x perls. It is a syntax error to write things like: my @x = apply { s/foo/bar/ } qw{ foo bar baz }; It has to be written as either my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz'; or my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/; Perl 5.5.x and Perl 5.8.x don't suffer from this limitation. If you have a functionality that you could imagine being in this module, please drop me a line. This module's policy will be less strict than L's when it comes to additions as it isn't a core module. When you report bugs, it would be nice if you could additionally give me the output of your program with the environment variable C set to a true value. That way I know where to look for the problem (in XS, pure-Perl or possibly both). =head1 SUPPORT Bugs should always be submitted via the CPAN bug tracker. L =head1 THANKS Credits go to a number of people: Steve Purkis for giving me namespace advice and James Keenan and Terrence Branno for their effort of keeping the CPAN tidier by making L obsolete. Brian McCauley suggested the inclusion of apply() and provided the pure-Perl implementation for it. Eric J. Roode asked me to add all functions from his module C into this one. With minor modifications, the pure-Perl implementations of those are by him. The bunch of people who almost immediately pointed out the many problems with the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN testers). A particularly nasty memory leak was spotted by Thomas A. Lowery. Lars Thegler made me aware of problems with older Perl versions. Anno Siegel de-orphaned each_arrayref(). David Filmer made me aware of a problem in each_arrayref that could ultimately lead to a segfault. Ricardo Signes suggested the inclusion of part() and provided the Perl-implementation. Robin Huston kindly fixed a bug in perl's MULTICALL API to make the XS-implementation of part() work. =head1 TODO A pile of requests from other people is still pending further processing in my mailbox. This includes: =over 4 =item * List::Util export pass-through Allow B to pass-through the regular L functions to end users only need to C the one module. =item * uniq_by(&@) Use code-reference to extract a key based on which the uniqueness is determined. Suggested by Aaron Crane. =item * delete_index =item * random_item =item * random_item_delete_index =item * list_diff_hash =item * list_diff_inboth =item * list_diff_infirst =item * list_diff_insecond These were all suggested by Dan Muey. =item * listify Always return a flat list when either a simple scalar value was passed or an array-reference. Suggested by Mark Summersault. =back =head1 SEE ALSO L =head1 AUTHOR Adam Kennedy Eadamk@cpan.orgE Tassilo von Parseval Etassilo.von.parseval@rwth-aachen.deE =head1 COPYRIGHT AND LICENSE Some parts copyright 2011 Aaron Crane. Copyright 2004 - 2010 by Tassilo von Parseval This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. =cut List-MoreUtils-0.33/dhash.h0000644000175100017510000000633011616464330014131 0ustar adamadam#ifndef __DHASH_H__ #define __DHASH_H__ /* A special hash-type for use in part(). It is a store-only * hash in that all key/value pairs are put into the hash. Then it is sorted by * keys ascending with dhash_sort_final where the empty elements come at the end * of the internal array. This need for sorting is actually what prevents us from * using a dhash-based implementaion right now as it is the bottleneck for cases * with many very small partitions. * * It doesn't use a linked list for collision recovery. Instead, on collision it will * walk right in the array to find the first free spot. This search should never take * too long as it uses a fairly good integer-hash function. * * The 'step' parameter isn't currently used. */ #include /* for qsort() */ #define INITIAL_SIZE 4 typedef unsigned int hash_t; typedef struct { int key; AV *val; } dhash_val_t; typedef struct { int max; int size; int count; int step; dhash_val_t *ary; } dhash_t; void dhash_dump(dhash_t *h); int cmp (dhash_val_t *a, dhash_val_t *b) { /* all empty buckets should be at the end of the array */ if (!a->val) return 1; if (!b->val) return -1; return a->key - b->key; } dhash_t * dhash_init() { dhash_t *h; New(0, h, 1, dhash_t); Newz(0, h->ary, INITIAL_SIZE, dhash_val_t); h->max = 0; h->size = INITIAL_SIZE; h->count = 0; return h; } void dhash_destroy(dhash_t *h) { Safefree(h->ary); Safefree(h); } inline hash_t HASH(register hash_t k) { k += (k << 12); k ^= (k >> 22); k += (k << 4); k ^= (k >> 9); k += (k << 10); k ^= (k >> 2); k += (k << 7); k ^= (k >> 12); return k; } void dhash_insert(dhash_t *h, int key, SV *sv, register hash_t hash) { while (h->ary[hash].val && h->ary[hash].key != key) hash = (hash + 1) % h->size; if (!h->ary[hash].val) { h->ary[hash].val = newAV(); h->ary[hash].key = key; h->count++; } av_push(h->ary[hash].val, sv); SvREFCNT_inc(sv); } void dhash_resize(dhash_t *h) { register int i; register hash_t hash; dhash_val_t *old = h->ary; h->size <<= 1; h->count = 0; Newz(0, h->ary, h->size, dhash_val_t); for (i = 0; i < h->size>>1; ++i) { if (!old[i].val) continue; hash = HASH(old[i].key) % h->size; while (h->ary[hash].val) hash = (hash + 1) % h->size; h->ary[hash] = old[i]; ++h->count; } Safefree(old); } void dhash_store(dhash_t *h, int key, SV *val) { hash_t hash; if ((double)h->count / (double)h->size > 0.75) dhash_resize(h); hash = HASH(key) % h->size; dhash_insert(h, key, val, hash); if (key > h->max) h->max = key; } /* Once this is called, the hash is no longer useable. The only thing * that may be done with it is iterate over h->ary to get the values * sorted by keys */ void dhash_sort_final(dhash_t *h) { qsort(h->ary, h->size, sizeof(dhash_val_t), (int(*)(const void*,const void*))cmp); } void dhash_dump(dhash_t *h) { int i; fprintf(stderr, "max=%i, size=%i, count=%i, ary=%p\n", h->max, h->size, h->count, h->ary); for (i = 0; i < h->size; i++) { fprintf(stderr, "%2i: key=%-5i => val=(AV*)%p\n", i, h->ary[i].key, h->ary[i].val); } } #endif List-MoreUtils-0.33/MoreUtils.xs0000644000175100017510000006513011616464330015173 0ustar adamadam#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #ifndef PERL_VERSION # include # if !(defined(PERL_VERSION) || (SUBVERSION > 0 && defined(PATCHLEVEL))) # include # endif # define PERL_REVISION 5 # define PERL_VERSION PATCHLEVEL # define PERL_SUBVERSION SUBVERSION #endif #ifndef aTHX # define aTHX # define pTHX #endif /* multicall.h is all nice and * fine but wont work on perl < 5.6.0 */ #if PERL_VERSION > 5 # include "multicall.h" #else # define dMULTICALL \ OP *_op; \ PERL_CONTEXT *cx; \ SV **newsp; \ U8 hasargs = 0; \ bool oldcatch = CATCH_GET # define PUSH_MULTICALL(cv) \ _op = CvSTART(cv); \ SAVESPTR(CvROOT(cv)->op_ppaddr); \ CvROOT(cv)->op_ppaddr = PL_ppaddr[OP_NULL]; \ SAVESPTR(PL_curpad); \ PL_curpad = AvARRAY((AV*)AvARRAY(CvPADLIST(cv))[1]); \ SAVETMPS; \ SAVESPTR(PL_op); \ CATCH_SET(TRUE); \ PUSHBLOCK(cx, CXt_SUB, SP); \ PUSHSUB(cx) # define MULTICALL \ PL_op = _op; \ CALLRUNOPS() # define POP_MULTICALL \ POPBLOCK(cx,PL_curpm); \ CATCH_SET(oldcatch); \ SPAGAIN #endif /* Some platforms have strict exports. And before 5.7.3 cxinc (or Perl_cxinc) was not exported. Therefore platforms like win32, VMS etc have problems so we redefine it here -- GMB */ #if PERL_VERSION < 7 /* Not in 5.6.1. */ # define SvUOK(sv) SvIOK_UV(sv) # ifdef cxinc # undef cxinc # endif # define cxinc() my_cxinc(aTHX) static I32 my_cxinc(pTHX) { cxstack_max = cxstack_max * 3 / 2; Renew(cxstack, cxstack_max + 1, struct context); /* XXX should fix CXINC macro */ return cxstack_ix + 1; } #endif #if PERL_VERSION < 6 # define NV double # define LEAVESUB(cv) \ { \ if (cv) { \ SvREFCNT_dec(cv); \ } \ } #endif #ifdef SVf_IVisUV # define slu_sv_value(sv) (SvIOK(sv)) ? (SvIOK_UV(sv)) ? (NV)(SvUVX(sv)) : (NV)(SvIVX(sv)) : (SvNV(sv)) #else # define slu_sv_value(sv) (SvIOK(sv)) ? (NV)(SvIVX(sv)) : (SvNV(sv)) #endif #ifndef Drand01 # define Drand01() ((rand() & 0x7FFF) / (double) ((unsigned long)1 << 15)) #endif #if PERL_VERSION < 5 # ifndef gv_stashpvn # define gv_stashpvn(n,l,c) gv_stashpv(n,c) # endif # ifndef SvTAINTED static bool sv_tainted(SV *sv) { if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) { MAGIC *mg = mg_find(sv, 't'); if (mg && ((mg->mg_len & 1) || (mg->mg_len & 2) && mg->mg_obj == sv)) return TRUE; } return FALSE; } # define SvTAINTED_on(sv) sv_magic((sv), Nullsv, 't', Nullch, 0) # define SvTAINTED(sv) (SvMAGICAL(sv) && sv_tainted(sv)) # endif # define PL_defgv defgv # define PL_op op # define PL_curpad curpad # define CALLRUNOPS runops # define PL_curpm curpm # define PL_sv_undef sv_undef # define PERL_CONTEXT struct context #endif #if (PERL_VERSION < 5) || (PERL_VERSION == 5 && PERL_SUBVERSION <50) # ifndef PL_tainting # define PL_tainting tainting # endif # ifndef PL_stack_base # define PL_stack_base stack_base # endif # ifndef PL_stack_sp # define PL_stack_sp stack_sp # endif # ifndef PL_ppaddr # define PL_ppaddr ppaddr # endif #endif #ifndef PTR2UV # define PTR2UV(ptr) (UV)(ptr) #endif #ifndef SvPV_nolen STRLEN N_A; # define SvPV_nolen(sv) SvPV(sv, N_A) #endif #ifndef call_sv # define call_sv perl_call_sv #endif #define WARN_OFF \ SV *oldwarn = PL_curcop->cop_warnings; \ PL_curcop->cop_warnings = pWARN_NONE; #define WARN_ON \ PL_curcop->cop_warnings = oldwarn; #define EACH_ARRAY_BODY \ register int i; \ arrayeach_args * args; \ HV *stash = gv_stashpv("List::MoreUtils_ea", TRUE); \ CV *closure = newXS(NULL, XS_List__MoreUtils__array_iterator, __FILE__); \ \ /* prototype */ \ sv_setpv((SV*)closure, ";$"); \ \ New(0, args, 1, arrayeach_args); \ New(0, args->avs, items, AV*); \ args->navs = items; \ args->curidx = 0; \ \ for (i = 0; i < items; i++) { \ args->avs[i] = (AV*)SvRV(ST(i)); \ SvREFCNT_inc(args->avs[i]); \ } \ \ CvXSUBANY(closure).any_ptr = args; \ RETVAL = newRV_noinc((SV*)closure); \ \ /* in order to allow proper cleanup in DESTROY-handler */ \ sv_bless(RETVAL, stash) /* #include "dhash.h" */ /* need this one for array_each() */ typedef struct { AV **avs; /* arrays over which to iterate in parallel */ int navs; /* number of arrays */ int curidx; /* the current index of the iterator */ } arrayeach_args; /* used for natatime */ typedef struct { SV **svs; int nsvs; int curidx; int natatime; } natatime_args; void insert_after (int idx, SV *what, AV *av) { register int i, len; av_extend(av, (len = av_len(av) + 1)); for (i = len; i > idx+1; i--) { SV **sv = av_fetch(av, i-1, FALSE); SvREFCNT_inc(*sv); av_store(av, i, *sv); } if (!av_store(av, idx+1, what)) SvREFCNT_dec(what); } MODULE = List::MoreUtils PACKAGE = List::MoreUtils void any (code,...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; GV *gv; HV *stash; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_NO; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { POP_MULTICALL; XSRETURN_YES; } } POP_MULTICALL; XSRETURN_NO; } void all (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_YES; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; i++) { GvSV(PL_defgv) = args[i]; MULTICALL; if (!SvTRUE(*PL_stack_sp)) { POP_MULTICALL; XSRETURN_NO; } } POP_MULTICALL; XSRETURN_YES; } void none (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_YES; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { POP_MULTICALL; XSRETURN_NO; } } POP_MULTICALL; XSRETURN_YES; } void notall (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_NO; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (!SvTRUE(*PL_stack_sp)) { POP_MULTICALL; XSRETURN_YES; } } POP_MULTICALL; XSRETURN_NO; } int true (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; I32 count = 0; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) goto done; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) count++; } POP_MULTICALL; done: RETVAL = count; } OUTPUT: RETVAL int false (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; I32 count = 0; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) goto done; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (!SvTRUE(*PL_stack_sp)) count++; } POP_MULTICALL; done: RETVAL = count; } OUTPUT: RETVAL int firstidx (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; RETVAL = -1; if (items > 1) { cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { RETVAL = i-1; break; } } POP_MULTICALL; } } OUTPUT: RETVAL int lastidx (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; RETVAL = -1; if (items > 1) { cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = items-1 ; i > 0 ; --i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { RETVAL = i-1; break; } } POP_MULTICALL; } } OUTPUT: RETVAL int insert_after (code, val, avref) SV *code; SV *val; SV *avref; PROTOTYPE: &$\@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; CV *cv; AV *av = (AV*)SvRV(avref); int len = av_len(av); RETVAL = 0; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 0; i <= len ; ++i) { GvSV(PL_defgv) = *av_fetch(av, i, FALSE); MULTICALL; if (SvTRUE(*PL_stack_sp)) { RETVAL = 1; break; } } POP_MULTICALL; if (RETVAL) { SvREFCNT_inc(val); insert_after(i, val, av); } } OUTPUT: RETVAL int insert_after_string (string, val, avref) SV *string; SV *val; SV *avref; PROTOTYPE: $$\@ CODE: { register int i; AV *av = (AV*)SvRV(avref); int len = av_len(av); register SV **sv; STRLEN slen = 0, alen; register char *str; register char *astr; RETVAL = 0; if (SvTRUE(string)) str = SvPV(string, slen); else str = NULL; for (i = 0; i <= len ; i++) { sv = av_fetch(av, i, FALSE); if (SvTRUE(*sv)) astr = SvPV(*sv, alen); else { astr = NULL; alen = 0; } if (slen == alen && memcmp(astr, str, slen) == 0) { RETVAL = 1; break; } } if (RETVAL) { SvREFCNT_inc(val); insert_after(i, val, av); } } OUTPUT: RETVAL void apply (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; CV *cv; SV **args = &PL_stack_base[ax]; I32 count = 0; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { GvSV(PL_defgv) = newSVsv(args[i]); MULTICALL; args[i-1] = GvSV(PL_defgv); } POP_MULTICALL; for(i = 1 ; i < items ; ++i) sv_2mortal(args[i-1]); done: XSRETURN(items-1); } void after (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i, j; HV *stash; CV *cv; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1; i < items; i++) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { break; } } POP_MULTICALL; for (j = i + 1; j < items; ++j) args[j-i-1] = args[j]; XSRETURN(items-i-1); } void after_incl (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i, j; HV *stash; CV *cv; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1; i < items; i++) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { break; } } POP_MULTICALL; for (j = i; j < items; j++) args[j-i] = args[j]; XSRETURN(items-i); } void before (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1; i < items; i++) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { break; } args[i-1] = args[i]; } POP_MULTICALL; XSRETURN(i-1); } void before_incl (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1; i < items; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; args[i-1] = args[i]; if (SvTRUE(*PL_stack_sp)) { ++i; break; } } POP_MULTICALL; XSRETURN(i-1); } void indexes (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i, j; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; if (items <= 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1, j = 0; i < items; i++) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) /* POP_MULTICALL can free mortal temporaries, so we defer * mortalising the returned values till after that's been * done */ args[j++] = newSViv(i-1); } POP_MULTICALL; for (i = 0; i < j; i++) sv_2mortal(args[i]); XSRETURN(j); } SV * lastval (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; RETVAL = &PL_sv_undef; if (items > 1) { cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = items-1 ; i > 0 ; --i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { /* see comment in indexes() */ SvREFCNT_inc(RETVAL = args[i]); break; } } POP_MULTICALL; } } OUTPUT: RETVAL SV * firstval (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i; HV *stash; GV *gv; I32 gimme = G_SCALAR; SV **args = &PL_stack_base[ax]; CV *cv; RETVAL = &PL_sv_undef; if (items > 1) { cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for (i = 1; i < items; ++i) { GvSV(PL_defgv) = args[i]; MULTICALL; if (SvTRUE(*PL_stack_sp)) { /* see comment in indexes() */ SvREFCNT_inc(RETVAL = args[i]); break; } } POP_MULTICALL; } } OUTPUT: RETVAL void _array_iterator (method = "") char *method; PROTOTYPE: ;$ CODE: { register int i; int exhausted = 1; /* 'cv' is the hidden argument with which XS_List__MoreUtils__array_iterator (this XSUB) * is called. The closure_arg struct is stored in this CV. */ #define ME_MYSELF_AND_I cv arrayeach_args *args = (arrayeach_args*)CvXSUBANY(ME_MYSELF_AND_I).any_ptr; if (strEQ(method, "index")) { EXTEND(SP, 1); ST(0) = args->curidx > 0 ? sv_2mortal(newSViv(args->curidx-1)) : &PL_sv_undef; XSRETURN(1); } EXTEND(SP, args->navs); for (i = 0; i < args->navs; i++) { AV *av = args->avs[i]; if (args->curidx <= av_len(av)) { ST(i) = sv_2mortal(newSVsv(*av_fetch(av, args->curidx, FALSE))); exhausted = 0; continue; } ST(i) = &PL_sv_undef; } if (exhausted) XSRETURN_EMPTY; args->curidx++; XSRETURN(args->navs); } SV * each_array (...) PROTOTYPE: \@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@ CODE: { EACH_ARRAY_BODY; } OUTPUT: RETVAL SV * each_arrayref (...) CODE: { EACH_ARRAY_BODY; } OUTPUT: RETVAL #if 0 void _pairwise (code, ...) SV *code; PROTOTYPE: &\@\@ PPCODE: { #define av_items(a) (av_len(a)+1) register int i; AV *avs[2]; SV **oldsp; int nitems = 0, maxitems = 0; /* deref AV's for convenience and * get maximum items */ avs[0] = (AV*)SvRV(ST(1)); avs[1] = (AV*)SvRV(ST(2)); maxitems = av_items(avs[0]); if (av_items(avs[1]) > maxitems) maxitems = av_items(avs[1]); if (!PL_firstgv || !PL_secondgv) { SAVESPTR(PL_firstgv); SAVESPTR(PL_secondgv); PL_firstgv = gv_fetchpv("a", TRUE, SVt_PV); PL_secondgv = gv_fetchpv("b", TRUE, SVt_PV); } oldsp = PL_stack_base; EXTEND(SP, maxitems); ENTER; for (i = 0; i < maxitems; i++) { int nret; SV **svp = av_fetch(avs[0], i, FALSE); GvSV(PL_firstgv) = svp ? *svp : &PL_sv_undef; svp = av_fetch(avs[1], i, FALSE); GvSV(PL_secondgv) = svp ? *svp : &PL_sv_undef; PUSHMARK(SP); PUTBACK; nret = call_sv(code, G_EVAL|G_ARRAY); if (SvTRUE(ERRSV)) croak("%s", SvPV_nolen(ERRSV)); SPAGAIN; nitems += nret; while (nret--) { SvREFCNT_inc(*PL_stack_sp++); } } PL_stack_base = oldsp; LEAVE; XSRETURN(nitems); } #endif void pairwise (code, ...) SV *code; PROTOTYPE: &\@\@ PPCODE: { #define av_items(a) (av_len(a)+1) /* This function is not quite as efficient as it ought to be: We call * 'code' multiple times and want to gather its return values all in * one list. However, each call resets the stack pointer so there is no * obvious way to get the return values onto the stack without making * intermediate copies of the pointers. The above disabled solution * would be more efficient. Unfortunately it doesn't work (and, as of * now, wouldn't deal with 'code' returning more than one value). * * The current solution is a fair trade-off. It only allocates memory * for a list of SV-pointers, as many as there are return values. It * temporarily stores 'code's return values in this list and, when * done, copies them down to SP. */ register int i, j; AV *avs[2]; SV **oldsp; register SV **buf, **p; /* gather return values here and later copy down to SP */ int alloc; int nitems = 0, maxitems = 0; register int d; /* deref AV's for convenience and * get maximum items */ avs[0] = (AV*)SvRV(ST(1)); avs[1] = (AV*)SvRV(ST(2)); maxitems = av_items(avs[0]); if (av_items(avs[1]) > maxitems) maxitems = av_items(avs[1]); if (!PL_firstgv || !PL_secondgv) { SAVESPTR(PL_firstgv); SAVESPTR(PL_secondgv); PL_firstgv = gv_fetchpv("a", TRUE, SVt_PV); PL_secondgv = gv_fetchpv("b", TRUE, SVt_PV); } New(0, buf, alloc = maxitems, SV*); ENTER; for (d = 0, i = 0; i < maxitems; i++) { int nret; SV **svp = av_fetch(avs[0], i, FALSE); GvSV(PL_firstgv) = svp ? *svp : &PL_sv_undef; svp = av_fetch(avs[1], i, FALSE); GvSV(PL_secondgv) = svp ? *svp : &PL_sv_undef; PUSHMARK(SP); PUTBACK; nret = call_sv(code, G_EVAL|G_ARRAY); if (SvTRUE(ERRSV)) { Safefree(buf); croak("%s", SvPV_nolen(ERRSV)); } SPAGAIN; nitems += nret; if (nitems > alloc) { alloc <<= 2; Renew(buf, alloc, SV*); } for (j = nret-1; j >= 0; j--) { /* POPs would return elements in reverse order */ buf[d] = sp[-j]; d++; } sp -= nret; } LEAVE; EXTEND(SP, nitems); p = buf; for (i = 0; i < nitems; i++) ST(i) = *p++; Safefree(buf); XSRETURN(nitems); } void _natatime_iterator () PROTOTYPE: CODE: { register int i; int nret; /* 'cv' is the hidden argument with which XS_List__MoreUtils__array_iterator (this XSUB) * is called. The closure_arg struct is stored in this CV. */ #define ME_MYSELF_AND_I cv natatime_args *args = (natatime_args*)CvXSUBANY(ME_MYSELF_AND_I).any_ptr; nret = args->natatime; EXTEND(SP, nret); for (i = 0; i < args->natatime; i++) { if (args->curidx < args->nsvs) { ST(i) = sv_2mortal(newSVsv(args->svs[args->curidx++])); } else { XSRETURN(i); } } XSRETURN(nret); } SV * natatime (n, ...) int n; PROTOTYPE: $@ CODE: { register int i; natatime_args * args; HV *stash = gv_stashpv("List::MoreUtils_na", TRUE); CV *closure = newXS(NULL, XS_List__MoreUtils__natatime_iterator, __FILE__); /* must NOT set prototype on iterator: * otherwise one cannot write: &$it */ /* !! sv_setpv((SV*)closure, ""); !! */ New(0, args, 1, natatime_args); New(0, args->svs, items-1, SV*); args->nsvs = items-1; args->curidx = 0; args->natatime = n; for (i = 1; i < items; i++) SvREFCNT_inc(args->svs[i-1] = ST(i)); CvXSUBANY(closure).any_ptr = args; RETVAL = newRV_noinc((SV*)closure); /* in order to allow proper cleanup in DESTROY-handler */ sv_bless(RETVAL, stash); } OUTPUT: RETVAL void mesh (...) PROTOTYPE: \@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@ CODE: { register int i, j, maxidx = -1; AV **avs; New(0, avs, items, AV*); for (i = 0; i < items; i++) { avs[i] = (AV*)SvRV(ST(i)); if (av_len(avs[i]) > maxidx) maxidx = av_len(avs[i]); } EXTEND(SP, items * (maxidx + 1)); for (i = 0; i <= maxidx; i++) for (j = 0; j < items; j++) { SV **svp = av_fetch(avs[j], i, FALSE); ST(i*items + j) = svp ? sv_2mortal(newSVsv(*svp)) : &PL_sv_undef; } Safefree(avs); XSRETURN(items * (maxidx + 1)); } void uniq (...) PROTOTYPE: @ CODE: { register int i, count = 0; HV *hv = newHV(); sv_2mortal(newRV_noinc((SV*)hv)); /* don't build return list in scalar context */ if (GIMME == G_SCALAR) { for (i = 0; i < items; i++) { if (!hv_exists_ent(hv, ST(i), 0)) { count++; hv_store_ent(hv, ST(i), &PL_sv_yes, 0); } } ST(0) = sv_2mortal(newSViv(count)); XSRETURN(1); } /* list context: populate SP with mortal copies */ for (i = 0; i < items; i++) { if (!hv_exists_ent(hv, ST(i), 0)) { ST(count) = sv_2mortal(newSVsv(ST(i))); count++; hv_store_ent(hv, ST(i), &PL_sv_yes, 0); } } XSRETURN(count); } void minmax (...) PROTOTYPE: @ CODE: { register int i; register SV *minsv, *maxsv, *asv, *bsv; register double min, max, a, b; if (!items) XSRETURN_EMPTY; minsv = maxsv = ST(0); min = max = slu_sv_value(minsv); if (items == 1) { EXTEND(SP, 1); ST(0) = ST(1) = minsv; XSRETURN(2); } for (i = 1; i < items; i += 2) { asv = ST(i-1); bsv = ST(i); a = slu_sv_value(asv); b = slu_sv_value(bsv); if (a <= b) { if (min > a) { min = a; minsv = asv; } if (max < b) { max = b; maxsv = bsv; } } else { if (min > b) { min = b; minsv = bsv; } if (max < a) { max = a; maxsv = asv; } } } if (items & 1) { asv = ST(items-2); bsv = ST(items-1); a = slu_sv_value(asv); b = slu_sv_value(bsv); if (a <= b) { if (min > a) { min = a; minsv = asv; } if (max < b) { max = b; maxsv = bsv; } } else { if (min > b) { min = b; minsv = bsv; } if (max < a) { max = a; maxsv = asv; } } } ST(0) = minsv; ST(1) = maxsv; XSRETURN(2); } void part (code, ...) SV *code; PROTOTYPE: &@ CODE: { dMULTICALL; register int i, j; HV *stash; GV *gv; I32 gimme = G_SCALAR; I32 count = 0; SV **args = &PL_stack_base[ax]; CV *cv; AV **tmp = NULL; int last = 0; if (items == 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { int idx; GvSV(PL_defgv) = args[i]; MULTICALL; idx = SvIV(*PL_stack_sp); if (idx < 0 && (idx += last) < 0) croak("Modification of non-creatable array value attempted, subscript %i", idx); if (idx >= last) { int oldlast = last; last = idx + 1; Renew(tmp, last, AV*); Zero(tmp + oldlast, last - oldlast, AV*); } if (!tmp[idx]) tmp[idx] = newAV(); av_push(tmp[idx], args[i]); SvREFCNT_inc(args[i]); } POP_MULTICALL; EXTEND(SP, last); for (i = 0; i < last; ++i) { if (tmp[i]) ST(i) = sv_2mortal(newRV_noinc((SV*)tmp[i])); else ST(i) = &PL_sv_undef; } Safefree(tmp); XSRETURN(last); } #if 0 void part_dhash (code, ...) SV *code; PROTOTYPE: &@ CODE: { /* We might want to keep this dhash-implementation. * It is currently slower than the above but it uses less * memory for sparse parts such as * @part = part { 10_000_000 } 1 .. 100_000; * Maybe there's a way to optimize dhash.h to get more speed * from it. */ dMULTICALL; register int i, j, lastidx = -1; int max; HV *stash; GV *gv; I32 gimme = G_SCALAR; I32 count = 0; SV **args = &PL_stack_base[ax]; CV *cv; dhash_t *h = dhash_init(); if (items == 1) XSRETURN_EMPTY; cv = sv_2cv(code, &stash, &gv, 0); PUSH_MULTICALL(cv); SAVESPTR(GvSV(PL_defgv)); for(i = 1 ; i < items ; ++i) { int idx; GvSV(PL_defgv) = args[i]; MULTICALL; idx = SvIV(*PL_stack_sp); if (idx < 0 && (idx += h->max) < 0) croak("Modification of non-creatable array value attempted, subscript %i", idx); dhash_store(h, idx, args[i]); } POP_MULTICALL; dhash_sort_final(h); EXTEND(SP, max = h->max+1); i = 0; lastidx = -1; while (i < h->count) { int retidx = h->ary[i].key; int fill = retidx - lastidx - 1; for (j = 0; j < fill; j++) { ST(retidx - j - 1) = &PL_sv_undef; } ST(retidx) = newRV_noinc((SV*)h->ary[i].val); i++; lastidx = retidx; } dhash_destroy(h); XSRETURN(max); } #endif void _XScompiled () CODE: XSRETURN_YES; MODULE = List::MoreUtils PACKAGE = List::MoreUtils_ea void DESTROY(sv) SV *sv; CODE: { register int i; CV *code = (CV*)SvRV(sv); arrayeach_args *args = CvXSUBANY(code).any_ptr; if (args) { for (i = 0; i < args->navs; ++i) SvREFCNT_dec(args->avs[i]); Safefree(args->avs); Safefree(args); CvXSUBANY(code).any_ptr = NULL; } } MODULE = List::MoreUtils PACKAGE = List::MoreUtils_na void DESTROY(sv) SV *sv; CODE: { register int i; CV *code = (CV*)SvRV(sv); natatime_args *args = CvXSUBANY(code).any_ptr; if (args) { for (i = 0; i < args->nsvs; ++i) SvREFCNT_dec(args->svs[i]); Safefree(args->svs); Safefree(args); CvXSUBANY(code).any_ptr = NULL; } } List-MoreUtils-0.33/MANIFEST0000644000175100017510000000043711616464406014030 0ustar adamadamChanges dhash.h lib/List/MoreUtils.pm LICENSE Makefile.PL MANIFEST This list of files MoreUtils.xs multicall.h README sanexs.c t/01_compile.t t/02_perl.t t/03_xs.t t/lib/Test.pm xt/meta.t xt/pmv.t xt/pod.t META.yml Module meta-data (added by MakeMaker) List-MoreUtils-0.33/t/0000755000175100017510000000000011616464406013136 5ustar adamadamList-MoreUtils-0.33/t/lib/0000755000175100017510000000000011616464406013704 5ustar adamadamList-MoreUtils-0.33/t/lib/Test.pm0000644000175100017510000005464011616464330015166 0ustar adamadampackage t::lib::Test; use 5.00503; use strict; use Test::More; use List::MoreUtils ':all'; # Run all tests sub run { plan tests => 184; test_any(); test_all(); test_none(); test_notall(); test_true(); test_false(); test_firstidx(); test_lastidx(); test_insert_after(); test_insert_after_string(); test_apply(); test_indexes(); test_before(); test_before_incl(); test_after(); test_after_incl(); test_firstval(); test_lastval(); test_each_array(); test_pairwise(); test_natatime(); test_zip(); test_mesh(); test_uniq(); test_part(); test_minmax(); } ###################################################################### # Test code intentionally ignorant of implementation (Pure Perl or XS) # The any function should behave identically to # !! grep CODE LIST sub test_any { # Normal cases my @list = ( 1 .. 10000 ); is_true( any { $_ == 5000 } @list ); is_true( any { $_ == 5000 } 1 .. 10000 ); is_true( any { defined } @list ); is_false( any { not defined } @list ); is_true( any { not defined } undef ); is_false( any { } ); leak_free_ok(any => sub { my $ok = any { $_ == 5000 } @list; my $ok2 = any { $_ == 5000 } 1 .. 10000; }); leak_free_ok('any with a coderef that dies' => sub { # This test is from Kevin Ryde; see RT#48669 eval { my $ok = any { die } 1 }; }); } sub test_all { # Normal cases my @list = ( 1 .. 10000 ); is_true( all { defined } @list ); is_true( all { $_ > 0 } @list ); is_false( all { $_ < 5000 } @list ); is_true( all { } ); leak_free_ok(all => sub { my $ok = all { $_ == 5000 } @list; my $ok2 = all { $_ == 5000 } 1 .. 10000; }); } sub test_none { # Normal cases my @list = ( 1 .. 10000 ); is_true( none { not defined } @list ); is_true( none { $_ > 10000 } @list ); is_false( none { defined } @list ); is_true( none { } ); leak_free_ok(none => sub { my $ok = none { $_ == 5000 } @list; my $ok2 = none { $_ == 5000 } 1 .. 10000; }); } sub test_notall { # Normal cases my @list = ( 1 .. 10000 ); is_true( notall { ! defined } @list ); is_true( notall { $_ < 10000 } @list ); is_false( notall { $_ <= 10000 } @list ); is_false( notall { } ); leak_free_ok(notall => sub { my $ok = notall { $_ == 5000 } @list; my $ok2 = notall { $_ == 5000 } 1 .. 10000; }); } sub test_true { # The null set should return zero my $null_scalar = true { }; my @null_list = true { }; is( $null_scalar, 0, 'true(null) returns undef' ); is_deeply( \@null_list, [ 0 ], 'true(null) returns undef' ); # Normal cases my @list = ( 1 .. 10000 ); is( 10000, true { defined } @list ); is( 0, true { not defined } @list ); is( 1, true { $_ == 5000 } @list ); leak_free_ok(true => sub { my $n = true { $_ == 5000 } @list; my $n2 = true { $_ == 5000 } 1 .. 10000; }); } sub test_false { # The null set should return zero my $null_scalar = false { }; my @null_list = false { }; is( $null_scalar, 0, 'false(null) returns undef' ); is_deeply( \@null_list, [ 0 ], 'false(null) returns undef' ); # Normal cases my @list = ( 1 .. 10000 ); is( 10000, false { not defined } @list ); is( 0, false { defined } @list ); is( 1, false { $_ > 1 } @list ); leak_free_ok(false => sub { my $n = false { $_ == 5000 } @list; my $n2 = false { $_ == 5000 } 1 .. 10000; }); } sub test_firstidx { my @list = ( 1 .. 10000 ); is( 4999, firstidx { $_ >= 5000 } @list ); is( -1, firstidx { not defined } @list ); is( 0, firstidx { defined } @list ); is( -1, firstidx { } ); # Test the alias is( 4999, first_index { $_ >= 5000 } @list ); is( -1, first_index { not defined } @list ); is( 0, first_index { defined } @list ); is( -1, first_index { } ); leak_free_ok(firstidx => sub { my $i = firstidx { $_ >= 5000 } @list; my $i2 = firstidx { $_ >= 5000 } 1 .. 10000; }); } sub test_lastidx { my @list = ( 1 .. 10000 ); is( 9999, lastidx { $_ >= 5000 } @list ); is( -1, lastidx { not defined } @list ); is( 9999, lastidx { defined } @list ); is( -1, lastidx { } ); # Test aliases is( 9999, last_index { $_ >= 5000 } @list ); is( -1, last_index { not defined } @list ); is( 9999, last_index { defined } @list ); is( -1, last_index { } ); leak_free_ok(lastidx => sub { my $i = lastidx { $_ >= 5000 } @list; my $i2 = lastidx { $_ >= 5000 } 1 .. 10000; }); } sub test_insert_after { my @list = qw{This is a list}; insert_after { $_ eq "a" } "longer" => @list; is( join(' ', @list), "This is a longer list" ); insert_after { 0 } "bla" => @list; is( join(' ', @list), "This is a longer list" ); insert_after { $_ eq "list" } "!" => @list; is( join(' ', @list), "This is a longer list !" ); @list = ( qw{This is}, undef, qw{list} ); insert_after { not defined($_) } "longer" => @list; $list[2] = "a"; is( join(' ', @list), "This is a longer list" ); leak_free_ok(insert_after => sub { @list = qw{This is a list}; insert_after { $_ eq 'a' } "longer" => @list; }); } sub test_insert_after_string { my @list = qw{This is a list}; insert_after_string "a", "longer" => @list; is( join(' ', @list), "This is a longer list" ); @list = ( undef, qw{This is a list} ); insert_after_string "a", "longer", @list; shift @list; is( join(' ', @list), "This is a longer list" ); @list = ( "This\0", "is\0", "a\0", "list\0" ); insert_after_string "a\0", "longer\0", @list; is( join(' ', @list), "This\0 is\0 a\0 longer\0 list\0" ); leak_free_ok(insert_after_string => sub { @list = qw{This is a list}; insert_after_string "a", "longer", @list; }); } sub test_apply { # Test the null case my $null_scalar = apply { }; my @null_list = apply { }; is( $null_scalar, undef, 'apply(null) returns undef' ); is_deeply( \@null_list, [ ], 'apply(null) returns null list' ); # Normal cases my @list = ( 0 .. 9 ); my @list1 = apply { $_++ } @list; ok( arrayeq( \@list, [ 0 .. 9 ] ) ); ok( arrayeq( \@list1, [ 1 .. 10 ] ) ); @list = ( " foo ", " bar ", " ", "foobar" ); @list1 = apply { s/^\s+|\s+$//g } @list; ok( arrayeq( \@list, [ " foo ", " bar ", " ", "foobar" ] ) ); ok( arrayeq( \@list1, [ "foo", "bar", "", "foobar" ] ) ); my $item = apply { s/^\s+|\s+$//g } @list; is( $item, "foobar" ); # RT 38630 SCOPE: { # wrong results from apply() [XS] @list = ( 1 .. 4 ); @list1 = apply { grow_stack(); $_ = 5; } @list; ok( arrayeq( \@list, [ 1 .. 4 ] ) ); ok( arrayeq( \@list1, [ ( 5 ) x 4 ] ) ); } leak_free_ok(apply => sub { @list = ( 1 .. 4 ); @list1 = apply { grow_stack(); $_ = 5; } @list; }); } sub test_indexes { my @x = indexes { $_ > 5 } ( 4 .. 9 ); ok( arrayeq( \@x, [ 2..5 ] ) ); @x = indexes { $_ > 5 } ( 1 .. 4 ); is_deeply( \@x, [ ], 'Got the null list' ); leak_free_ok(indexes => sub { @x = indexes { $_ > 5 } ( 4 .. 9 ); @x = indexes { $_ > 5 } ( 1 .. 4 ); }); } # In the following, the @dummy variable is needed to circumvent # a parser glitch in the 5.6.x series. sub test_before { my @x = before { $_ % 5 == 0 } 1 .. 9; ok( arrayeq( \@x, [ 1, 2, 3, 4 ] ) ); @x = before { /b/ } my @dummy = qw{ bar baz }; is_deeply( \@x, [ ], 'Got the null list' ); @x = before { /f/ } @dummy = qw{ bar baz foo }; ok( arrayeq( \@x, [ qw{ bar baz } ] ) ); leak_free_ok(before => sub { @x = before { /f/ } @dummy = qw{ bar baz foo }; }); } # In the following, the @dummy variable is needed to circumvent # a parser glitch in the 5.6.x series. sub test_before_incl { my @x = before_incl { $_ % 5 == 0 } 1 .. 9; ok( arrayeq( \@x, [ 1, 2, 3, 4, 5 ] ) ); @x = before_incl { /foo/ } my @dummy = qw{ bar baz }; ok( arrayeq( \@x, [ qw{ bar baz } ] ) ); @x = before_incl { /f/ } @dummy = qw{ bar baz foo }; ok( arrayeq( \@x, [ qw{ bar baz foo } ] ) ); leak_free_ok(before_incl => sub { @x = before_incl { /z/ } @dummy = qw{ bar baz foo }; }); } # In the following, the @dummy variable is needed to circumvent # a parser glitch in the 5.6.x series. sub test_after { my @x = after { $_ % 5 == 0 } 1 .. 9; ok( arrayeq( \@x, [ 6, 7, 8, 9 ] ) ); @x = after { /foo/ } my @dummy = qw{ bar baz }; is_deeply( \@x, [ ], 'Got the null list' ); @x = after { /b/ } @dummy = qw{ bar baz foo }; ok( arrayeq( \@x, [ qw{ baz foo } ] ) ); leak_free_ok(after => sub { @x = after { /z/ } @dummy = qw{ bar baz foo }; }); } # In the following, the @dummy variable is needed to circumvent # a parser glitch in the 5.6.x series. sub test_after_incl { my @x = after_incl { $_ % 5 == 0 } 1 .. 9; ok( arrayeq( \@x, [ 5, 6, 7, 8, 9 ] ) ); @x = after_incl { /foo/ } my @dummy = qw{ bar baz }; is_deeply( \@x, [ ], 'Got the null list' ); @x = after_incl { /b/ } @dummy = qw{ bar baz foo }; ok( arrayeq( \@x, [ qw{ bar baz foo } ] ) ); leak_free_ok(after_incl => sub { @x = after_incl { /z/ } @dummy = qw{ bar baz foo }; }); } sub test_firstval { my $x = firstval { $_ > 5 } 4 .. 9; is( $x, 6 ); $x = firstval { $_ > 5 } 1 .. 4; is( $x, undef ); # Test aliases $x = first_value { $_ > 5 } 4..9; is( $x, 6 ); $x = first_value { $_ > 5 } 1..4; is( $x, undef ); leak_free_ok(firstval => sub { $x = firstval { $_ > 5 } 4 .. 9; }); } sub test_lastval { my $x = lastval { $_ > 5 } 4..9; is( $x, 9 ); $x = lastval { $_ > 5 } 1..4; is( $x, undef ); # Test aliases $x = last_value { $_ > 5 } 4..9; is( $x, 9 ); $x = last_value { $_ > 5 } 1..4; is( $x, undef ); leak_free_ok(lastval => sub { $x = lastval { $_ > 5 } 4 .. 9; }); } sub test_each_array { SCOPE: { my @a = ( 7, 3, 'a', undef, 'r' ); my @b = qw{ a 2 -1 x }; my $it = each_array @a, @b; my (@r, @idx); while ( my ($a, $b) = $it->() ) { push @r, $a, $b; push @idx, $it->('index'); } # Do I segfault? I shouldn't. $it->(); ok( arrayeq( \@r, [ 7, 'a', 3, 2, 'a', -1, undef, 'x', 'r', undef ] ) ); ok( arrayeq( \@idx, [ 0 .. 4 ] ) ); # Testing two iterators on the same arrays in parallel @a = ( 1, 3, 5 ); @b = ( 2, 4, 6 ); my $i1 = each_array @a, @b; my $i2 = each_array @a, @b; @r = (); while ( my ($a, $b) = $i1->() and my ($c, $d) = $i2->() ) { push @r, $a, $b, $c, $d; } ok( arrayeq( \@r, [ 1, 2, 1, 2, 3, 4, 3, 4, 5, 6, 5, 6 ] ) ); # Input arrays must not be modified ok( arrayeq( \@a, [ 1, 3, 5 ] ) ); ok( arrayeq( \@b, [ 2, 4, 6 ] ) ); # This used to give "semi-panic: attempt to dup freed string" # See: my $ea = each_arrayref( [ 1 .. 26 ], [ 'A' .. 'Z' ] ); (@a, @b) = (); while ( my ($a, $b) = $ea->() ) { push @a, $a; push @b, $b; } ok( arrayeq( \@a, [ 1 .. 26 ] ) ); ok( arrayeq( \@b, [ 'A' .. 'Z' ] ) ); # And this even used to dump core my @nums = 1 .. 26; $ea = each_arrayref( \@nums, [ 'A' .. 'Z' ] ); (@a, @b) = (); while ( my ($a, $b) = $ea->() ) { push @a, $a; push @b, $b; } ok( arrayeq( \@a, [ 1 .. 26 ] ) ); ok( arrayeq( \@a, \@nums ) ); ok( arrayeq( \@b, ['A' .. 'Z' ] ) ); } SCOPE: { my @a = ( 7, 3, 'a', undef, 'r' ); my @b = qw/a 2 -1 x/; my $it = each_arrayref \@a, \@b; my (@r, @idx); while ( my ($a, $b) = $it->() ) { push @r, $a, $b; push @idx, $it->('index'); } # Do I segfault? I shouldn't. $it->(); ok( arrayeq( \@r, [ 7, 'a', 3, 2, 'a', -1, undef, 'x', 'r', undef ] ) ); ok( arrayeq( \@idx, [ 0..4 ] ) ); # Testing two iterators on the same arrays in parallel @a = (1, 3, 5); @b = (2, 4, 6); my $i1 = each_array @a, @b; my $i2 = each_array @a, @b; @r = (); while ( my ($a, $b) = $i1->() and my ($c, $d) = $i2->() ) { push @r, $a, $b, $c, $d; } ok( arrayeq( \@r, [ 1, 2, 1, 2, 3, 4, 3, 4, 5, 6, 5, 6 ] ) ); # Input arrays must not be modified ok( arrayeq( \@a, [ 1, 3, 5 ] ) ); ok( arrayeq( \@b, [ 2, 4, 6 ] ) ); } # Note that the leak_free_ok tests for each_array and each_arrayref # should not be run until either of them has been called at least once # in the current perl. That's because calling them the first time # causes the runtime to allocate some memory used for the OO structures # that their implementation uses internally. leak_free_ok(each_array => sub { my @a = (1); my $it = each_array @a; while ( my ($a) = $it->() ) { } }); leak_free_ok(each_arrayref => sub { my @a = (1); my $it = each_arrayref \@a; while ( my ($a) = $it->() ) { } }); } sub test_pairwise { my @a = (1, 2, 3, 4, 5); my @b = (2, 4, 6, 8, 10); my @c = pairwise { $a + $b } @a, @b; is( arrayeq( \@c, [ 3, 6, 9, 12, 15 ] ), 1, "pw1" ); @c = pairwise { $a * $b } @a, @b; # returns (2, 8, 18) is( arrayeq( \@c, [ 2, 8, 18, 32, 50 ] ), 1, "pw2" ); # Did we modify the input arrays? is( arrayeq( \@a, [ 1, 2, 3, 4, 5 ] ), 1, "pw3" ); is( arrayeq( \@b, [ 2, 4, 6, 8, 10 ] ), 1, "pw4" ); # $a and $b should be aliases: test @b = @a = (1, 2, 3); @c = pairwise { $a++; $b *= 2 } @a, @b; is( arrayeq( \@a, [ 2, 3, 4 ] ), 1, "pw5" ); is( arrayeq( \@b, [ 2, 4, 6 ] ), 1, "pw6" ); is( arrayeq( \@c, [ 2, 4, 6 ] ), 1, "pw7" ); # Test this one more thoroughly: the XS code looks flakey # correctness of pairwise_perl proved by human auditing. :-) sub pairwise_perl (&\@\@) { no strict; my $op = shift; local (*A, *B) = @_; # syms for caller's input arrays # Localise $a, $b my ($caller_a, $caller_b) = do { my $pkg = caller(); \*{$pkg.'::a'}, \*{$pkg.'::b'}; }; # Loop iteration limit my $limit = $#A > $#B? $#A : $#B; # This map expression is also the return value. local(*$caller_a, *$caller_b); map { # Assign to $a, $b as refs to caller's array elements (*$caller_a, *$caller_b) = \($A[$_], $B[$_]); $op->(); # perform the transformation } 0 .. $limit; } (@a, @b) = (); push @a, int rand(1000) for 0 .. rand(1000); push @b, int rand(1000) for 0 .. rand(1000); local $^W = 0; my @res1 = pairwise {$a+$b} @a, @b; my @res2 = pairwise_perl {$a+$b} @a, @b; ok( arrayeq(\@res1, \@res2) ); @a = qw/a b c/; @b = qw/1 2 3/; @c = pairwise { ($a, $b) } @a, @b; ok( arrayeq( \@c, [ qw/a 1 b 2 c 3/ ] ) ); # 88 # Test that a die inside the code-reference will not be trapped eval { pairwise { die "I died\n" } @a, @b }; is( $@, "I died\n" ); leak_free_ok(pairwise => sub { @a = (1); @b = (2); @c = pairwise { $a + $b } @a, @b; }); } sub test_natatime { my @x = ( 'a'..'g' ); my $it = natatime 3, @x; my @r; local $" = " "; while ( my @vals = $it->() ) { push @r, "@vals"; } is( arrayeq( \@r, [ 'a b c', 'd e f', 'g' ] ), 1, "natatime1" ); my @a = ( 1 .. 1000 ); $it = natatime 1, @a; @r = (); while ( my @vals = &$it ) { push @r, @vals; } is( arrayeq( \@r, \@a ), 1, "natatime2" ); leak_free_ok(natatime => sub { my @y = 1; my $it = natatime 2, @y; while ( my @vals = $it->() ) { # do nothing } }); } sub test_zip { SCOPE: { my @x = qw/a b c d/; my @y = qw/1 2 3 4/; my @z = zip @x, @y; ok( arrayeq(\@z, ['a', 1, 'b', 2, 'c', 3, 'd', 4]) ); } SCOPE: { my @a = ( 'x' ); my @b = ( '1', '2' ); my @c = qw/zip zap zot/; my @z = zip @a, @b, @c; ok( arrayeq( \@z, [ 'x', 1, 'zip', undef, 2, 'zap', undef, undef, 'zot' ] ) ); } SCOPE: { # Make array with holes my @a = ( 1 .. 10 ); my @d; $#d = 9; my @z = zip @a, @d; ok( arrayeq( \@z, [ 1, undef, 2, undef, 3, undef, 4, undef, 5, undef, 6, undef, 7, undef, 8, undef, 9, undef, 10, undef, ] ) ); } leak_free_ok(zip => sub { my @x = qw/a b c d/; my @y = qw/1 2 3 4/; my @z = zip @x, @y; }); } sub test_mesh { SCOPE: { my @x = qw/a b c d/; my @y = qw/1 2 3 4/; my @z = mesh @x, @y; ok( arrayeq( \@z, [ 'a', 1, 'b', 2, 'c', 3, 'd', 4 ] ) ); } SCOPE: { my @a = ('x'); my @b = ('1', '2'); my @c = qw/zip zap zot/; my @z = mesh @a, @b, @c; ok( arrayeq( \@z, [ 'x', 1, 'zip', undef, 2, 'zap', undef, undef, 'zot' ] ) ); } # Make array with holes SCOPE: { my @a = ( 1 .. 10 ); my @d; $#d = 9; my @z = mesh @a, @d; ok( arrayeq( \@z, [ 1, undef, 2, undef, 3, undef, 4, undef, 5, undef, 6, undef, 7, undef, 8, undef, 9, undef, 10, undef, ] ) ); } leak_free_ok(mesh => sub { my @x = qw/a b c d/; my @y = qw/1 2 3 4/; my @z = mesh @x, @y; }); } sub test_uniq { SCOPE: { my @a = map { ( 1 .. 1000 ) } 0 .. 1; my @u = uniq @a; ok( arrayeq( \@u, [ 1 .. 1000 ] ) ); my $u = uniq @a; is( 1000, $u ); } # Test aliases SCOPE: { my @a = map { ( 1 .. 1000 ) } 0 .. 1; my @u = distinct @a; ok( arrayeq( \@u, [ 1 .. 1000 ] ) ); my $u = distinct @a; is( 1000, $u ); } # Test support for undef values without warnings # SCOPE: { # my @warnings = (); # local $SIG{__WARN__} = sub { # push @warnings, @_; # }; # my @foo = ('a','b', undef, 'b', ''); # is_deeply( [ uniq @foo ], \@foo, 'undef is supported correctly' ); # is_deeply( \@warnings, [ ], 'No warnings during uniq check' ); # } leak_free_ok(uniq => sub { my @a = map { ( 1 .. 1000 ) } 0 .. 1; my @u = uniq @a; }); # This test (and the associated fix) are from Kevin Ryde; see RT#49796 leak_free_ok('uniq with exception in overloading stringify', sub { eval { my $obj = DieOnStringify->new; my @u = uniq $obj, $obj; }; eval { my $obj = DieOnStringify->new; my $u = uniq $obj, $obj; }; }); } sub test_part { my @list = 1 .. 12; my $i = 0; my @part = part { $i++ % 3 } @list; ok( arrayeq($part[0], [ 1, 4, 7, 10 ]) ); ok( arrayeq($part[1], [ 2, 5, 8, 11 ]) ); ok( arrayeq($part[2], [ 3, 6, 9, 12 ]) ); @part = part { 3 } @list; is( $part[0], undef ); is( $part[1], undef ); is( $part[2], undef ); ok( arrayeq($part[3], [ 1 .. 12 ]) ); eval { @part = part { -1 } @list; }; ok( $@ =~ /^Modification of non-creatable array value attempted, subscript -1/ ); $i = 0; @part = part { $i++ == 0 ? 0 : -1 } @list; ok( arrayeq($part[0], [ 1 .. 12 ]) ); local $^W = 0; @part = part { undef } @list; ok( arrayeq($part[0], [ 1 .. 12 ]) ); @part = part { 10000 } @list; ok( arrayeq($part[10000], [ @list ]) ); is( $part[0], undef ); is( $part[@part / 2], undef ); is( $part[9999], undef ); # Changing the list in place used to destroy # its elements due to a wrong refcnt @list = 1 .. 10; @list = part { $_ } @list; foreach ( 1 .. 10 ) { ok( arrayeq($list[$_], [ $_ ]) ); } leak_free_ok(part => sub { my @list = 1 .. 12; my $i = 0; my @part = part { $i++ % 3 } @list; }); leak_free_ok('part with stack-growing' => sub { # This test is from Kevin Ryde; see RT#38699 my @part = part { grow_stack(); 1024 } 'one', 'two'; }); } sub test_minmax { my @list = reverse 0 .. 10000; my ($min, $max) = minmax @list; is( $min, 0 ); is( $max, 10000 ); # Even number of elements push @list, 10001; ($min, $max) = minmax @list; is( $min, 0 ); is( $max, 10001 ); # Some floats @list = ( 0, -1.1, 3.14, 1 / 7, 10000, -10 / 3 ); ($min, $max) = minmax @list; # Floating-point comparison cunningly avoided is( sprintf("%.2f", $min), "-3.33" ); is( $max, 10000 ); # Test with a single negative list value my $input = -1; ($min, $max) = minmax $input; is( $min, -1 ); is( $max, -1 ); # Confirm output are independant copies of input $input = 1; is( $min, -1 ); is( $max, -1 ); $min = 2; is( $max, -1 ); leak_free_ok(minmax => sub { @list = ( 0, -1.1, 3.14, 1 / 7, 10000, -10 / 3 ); ($min, $max) = minmax @list; }); } ###################################################################### # Support Functions sub is_true { die "Expected 1 param" unless @_ == 1; is( $_[0], !0 ); } sub is_false { die "Expected 1 param" unless @_ == 1; is( $_[0], !1 ); } my @bigary = ( 1 ) x 500; sub func { } sub grow_stack { func(@bigary); } sub arrayeq { local $^W = 0; my $left = shift; my $right = shift; return 0 if @$left != @$right; foreach ( 0 .. $#$left ) { if ($left->[$_] ne $right->[$_]) { local $" = ", "; warn "(@$left) != (@$right)\n"; return 0; } } return 1; } sub leak_free_ok { my $name = shift; my $code = shift; SKIP: { skip 'Test::LeakTrace not installed', 1 unless eval { require Test::LeakTrace; 1 }; &Test::LeakTrace::no_leaks_ok($code, "No memory leaks in $name"); } } { package DieOnStringify; use overload '""' => \&stringify; sub new { bless {}, shift } sub stringify { die 'DieOnStringify exception' } } 1; List-MoreUtils-0.33/t/03_xs.t0000644000175100017510000000021611616464330014252 0ustar adamadam#!/usr/bin/perl use strict; BEGIN { $| = 1; $^W = 1; $ENV{LIST_MOREUTILS_PP} = 0; }; require t::lib::Test; t::lib::Test->run; List-MoreUtils-0.33/t/01_compile.t0000644000175100017510000000022211616464330015243 0ustar adamadam#!/usr/bin/perl use strict; BEGIN { $| = 1; $^W = 1; } use Test::More tests => 2; use_ok( 'List::MoreUtils' ); use_ok( 't::lib::Test' ); List-MoreUtils-0.33/t/02_perl.t0000644000175100017510000000021611616464330014561 0ustar adamadam#!/usr/bin/perl use strict; BEGIN { $| = 1; $^W = 1; $ENV{LIST_MOREUTILS_PP} = 1; }; require t::lib::Test; t::lib::Test->run; List-MoreUtils-0.33/Changes0000644000175100017510000001436711616464330014175 0ustar adamadamRevision history for Perl extension List-MoreUtils 0.33 Thu 4 Aug 2011 - Updated can_xs to fix a bug in it 0.32 Fri May 20 2011 - Production release, no other changes 0.31_02 Mon 21 Mar 2011 - More accurate detection of XS support (ADAMK) 0.31_01 Mon 21 Mar 2011 - Updating copyright year (ADAMK) - Teak documentation of all() and none() (WYANT) - Memory leak fixed for apply() and XS version restored (ARC) - Memory leak fixed for indexes() and XS version restored (ARC) - Memory leak fixed for part() and XS version restored (ARC) 0.30 Thu 16 Dec 2010 - Change the way we localise PERL_DL_NONLAZY to false to remove a warning that some people were seeing. The new approach is taken from the way that List::Util does it. 0.29 Wed 8 Dec 2010 - Removed an erroneous Test::NoWarnings dependency 0.28 Tue 7 Dec 2010 - Switching to a production release - Restored the regression test for RT #38630 from 0.23. As apply() was disabled in 0.27_04 this test will only act to validate the future XS restoration of apply(). - Adding uniq warning tests, disabled initially 0.27_04 Mon 6 Dec 2010 - The behaviour of any/all/none/notall has changed when passed a null list to treat a null list as a legitimate list. Instead of returning C the functions now return the following: any {} == false, all {} == true, none {} == true, notall {} == false. Resolves #40905: Returning undef when none is passed an empty - Disabled the leaking XS versions of part(), apply() and indexes() 0.27_03 Mon 6 Dec 2010 - General house cleaning 0.27_02 Wed 1 Dec 2010 - Reduced test suite peak memory consumption by 5-10 meg - Added the 'distinct' alias for the uniq function, for people that like their chained map/grep/sort pipelines with a SQL'ish flavour. - Expanded test suite for the any() group of functions. - The any() group of functions now strictly always return scalar boolean true, false and undef to match the XS version. 0.27_01 Wed 1 Dec 2010 - Refactored the split test scripts into a common test module to be shared between both the Perl and XS versions. - Reapply fix for http://rt.cpan.org/Ticket/Display.html?id=39847 "minmax error: unpredictable results with lists of 1 element" 0.26 Tue 23 Nov 2010 - No changes - Some parts of the CPAN cloud were confusing my 0.24 release with the older deleted 0.24. Bumping version past Tassilo's to clarify things. 0.24 Mon 22 Nov 2010 - No changes, switching to a production version 0.23_01 Sat 25 Sep 2010 - First attempt at repackaging the List::MoreUtils code in Makefile.PL and release toolchain similar to Params::Util 0.22 Sun Jul 2 11:25:39 EDT 2006 - SvPV_nolen doesn't exist on pre 5.6 perls 0.21 Sun Jun 18 07:59:06 EDT 2006 - propagate dies from inside the code-reference of pairwise to caller 0.20 Tue Apr 25 15:43:57 EDT 2006 - part() would destroy the list elements when changing an array in place (@list = part { ... } @list) 0.19 Mon Mar 13 19:07:37 CET 2006 - working down myself the queue of suggestions: part() added (Ricardo SIGNES ) 0.18 Sat Feb 25 08:55:48 CET 2006 - each_arrayref (XS) couldn't deal with refs to list literals (brought up by David Filmer in comp.lang.perl.misc) 0.17 Wed Dec 7 10:45:43 CET 2005 - each_arrayref had no XS implementation and wasn't mentioned in the PODs (patch by Anno Siegel ) 0.16 Mon Nov 14 09:57:28 CET 2005 - a dangling semicolon in some macros prevented the XS portion to compile on some compilers (Lars Thegler ) 0.15 Fri Nov 11 09:23:29 CET 2005 - 0.13 and 0.14 broke the module on 5.6.x (spotted by Thomas A. Lowery ) - internals changed to make use of the new MULTICALL API which had to be backported to 5.005_x 0.14 Thu Nov 10 13:08:03 CET 2005 - 0.13 fixed the leaks but rendered the XS part uncompilable for perls < 5.6.0: Fixed (spotted by Lars Thegler ) 0.13 Wed Nov 9 16:29:02 CET 2005 - nearly all functions receiving a CODE-block as first argument had a hefty memory-leak: Fixed (spotted by Thomas A. Lowery ) 0.12 Wed Sep 28 08:09:08 CEST 2005 - first_index and each_arrayref weren't exportable (spotted by Darren Duncan) 0.11 Tue Sep 27 08:15:22 CEST 2005 - make sure that Test::Pod and Test::Pod::Coverage are installed in the required minimum versions (thanks to Ricardo Signes ) 0.10 Fri Apr 1 19:43:48 CEST 2005 - new function minmax() with comparisons in O(3n/2 - 2) - some POD corrections (Adam Kennedy) - POD- and POD-coverage tests 0.09 Sat Dec 4 07:17:10 CET 2004 - 0.08 only fixed uniq() for scalar context 0.08 Fri Dec 3 17:11:14 CET 2004 - uniq() was not mentioned in the perldocs and only had the XS implementation - uniq() also produced wrong results on 5.8.0 (thanks to Slaven Rezic for spotting it and suggesting a workaround) - the test-suite triggered a bug in 5.6.x perls - the test-suite now tests both the XS- and Perl-implementation - a wrong example in the perldocs fixed (Ron Savage) 0.07 Wed Dec 1 07:56:08 CET 2004 - new functions: after, after_incl, before, before_incl, indexes lastval, firstval, pairwise, each_array, natatime, mesh (all from Eric J. Roodes' List::MoreUtil). 0.06 Sun Nov 14 06:33:52 CET 2004 - new function 'apply' on behalf of Brian McCauley () 0.05 Sat Sep 18 09:06:22 CEST 2004 - merged in insert_after() and insert_after_string() from List::Utils which is now obsolete (thanks to James Keenan and Terrence Brannon ) 0.04 Sat Jul 10 08:00:11 CEST 2004 - renamed to List::MoreUtils on suggestion by Steve Purkis 0.03 Fri Jul 9 07:54:09 CEST 2004 - some compilers don't like the stale goto labels without any statement following. Fixed. (Robert Rothenberg ) 0.02 Thu Jul 8 08:07:39 CEST 2004 - added Perl implementations of all functions as a fallback (Adam Kennedy ) 0.01 Mon Jul 5 07:58:40 2004 - original version; created by h2xs 1.23 with options -b 5.5.3 -A -n List::Any List-MoreUtils-0.33/multicall.h0000644000175100017510000001067311616464330015035 0ustar adamadam/* multicall.h (version 1.0) * * Implements a poor-man's MULTICALL interface for old versions * of perl that don't offer a proper one. Intended to be compatible * with 5.6.0 and later. * */ #ifdef dMULTICALL #define REAL_MULTICALL #else #undef REAL_MULTICALL /* In versions of perl where MULTICALL is not defined (i.e. prior * to 5.9.4), Perl_pad_push is not exported either. It also has * an extra argument in older versions; certainly in the 5.8 series. * So we redefine it here. */ #ifndef AVf_REIFY # ifdef SVpav_REIFY # define AVf_REIFY SVpav_REIFY # else # error Neither AVf_REIFY nor SVpav_REIFY is defined # endif #endif #ifndef AvFLAGS # define AvFLAGS SvFLAGS #endif static void multicall_pad_push(pTHX_ AV *padlist, int depth) { if (depth <= AvFILLp(padlist)) return; { SV** const svp = AvARRAY(padlist); AV* const newpad = newAV(); SV** const oldpad = AvARRAY(svp[depth-1]); I32 ix = AvFILLp((AV*)svp[1]); const I32 names_fill = AvFILLp((AV*)svp[0]); SV** const names = AvARRAY(svp[0]); AV *av; for ( ;ix > 0; ix--) { if (names_fill >= ix && names[ix] != &PL_sv_undef) { const char sigil = SvPVX(names[ix])[0]; if ((SvFLAGS(names[ix]) & SVf_FAKE) || sigil == '&') { /* outer lexical or anon code */ av_store(newpad, ix, SvREFCNT_inc(oldpad[ix])); } else { /* our own lexical */ SV *sv; if (sigil == '@') sv = (SV*)newAV(); else if (sigil == '%') sv = (SV*)newHV(); else sv = NEWSV(0, 0); av_store(newpad, ix, sv); SvPADMY_on(sv); } } else if (IS_PADGV(oldpad[ix]) || IS_PADCONST(oldpad[ix])) { av_store(newpad, ix, SvREFCNT_inc(oldpad[ix])); } else { /* save temporaries on recursion? */ SV * const sv = NEWSV(0, 0); av_store(newpad, ix, sv); SvPADTMP_on(sv); } } av = newAV(); av_extend(av, 0); av_store(newpad, 0, (SV*)av); AvFLAGS(av) = AVf_REIFY; av_store(padlist, depth, (SV*)newpad); AvFILLp(padlist) = depth; } } #define dMULTICALL \ SV **newsp; /* set by POPBLOCK */ \ PERL_CONTEXT *cx; \ CV *multicall_cv; \ OP *multicall_cop; \ bool multicall_oldcatch; \ U8 hasargs = 0 /* Between 5.9.1 and 5.9.2 the retstack was removed, and the return op is now stored on the cxstack. */ #define HAS_RETSTACK (\ PERL_REVISION < 5 || \ (PERL_REVISION == 5 && PERL_VERSION < 9) || \ (PERL_REVISION == 5 && PERL_VERSION == 9 && PERL_SUBVERSION < 2) \ ) /* PUSHSUB is defined so differently on different versions of perl * that it's easier to define our own version than code for all the * different possibilities. */ #if HAS_RETSTACK # define PUSHSUB_RETSTACK(cx) #else # define PUSHSUB_RETSTACK(cx) cx->blk_sub.retop = Nullop; #endif #define MULTICALL_PUSHSUB(cx, the_cv) \ cx->blk_sub.cv = the_cv; \ cx->blk_sub.olddepth = CvDEPTH(the_cv); \ cx->blk_sub.hasargs = hasargs; \ cx->blk_sub.lval = PL_op->op_private & \ (OPpLVAL_INTRO|OPpENTERSUB_INARGS); \ PUSHSUB_RETSTACK(cx) \ if (!CvDEPTH(the_cv)) { \ (void)SvREFCNT_inc(the_cv); \ (void)SvREFCNT_inc(the_cv); \ SAVEFREESV(the_cv); \ } #define PUSH_MULTICALL(the_cv) \ STMT_START { \ CV *_nOnclAshIngNamE_ = the_cv; \ AV* padlist = CvPADLIST(_nOnclAshIngNamE_); \ multicall_cv = _nOnclAshIngNamE_; \ ENTER; \ multicall_oldcatch = CATCH_GET; \ SAVESPTR(CvROOT(multicall_cv)->op_ppaddr); \ CvROOT(multicall_cv)->op_ppaddr = PL_ppaddr[OP_NULL]; \ SAVETMPS; SAVEVPTR(PL_op); \ CATCH_SET(TRUE); \ PUSHSTACKi(PERLSI_SORT); \ PUSHBLOCK(cx, CXt_SUB, PL_stack_sp); \ MULTICALL_PUSHSUB(cx, multicall_cv); \ if (++CvDEPTH(multicall_cv) >= 2) { \ PERL_STACK_OVERFLOW_CHECK(); \ multicall_pad_push(aTHX_ padlist, CvDEPTH(multicall_cv)); \ } \ SAVECOMPPAD(); \ PL_comppad = (AV*) (AvARRAY(padlist)[CvDEPTH(multicall_cv)]); \ PL_curpad = AvARRAY(PL_comppad); \ multicall_cop = CvSTART(multicall_cv); \ } STMT_END #define MULTICALL \ STMT_START { \ PL_op = multicall_cop; \ CALLRUNOPS(aTHX); \ } STMT_END #define POP_MULTICALL \ STMT_START { \ CvDEPTH(multicall_cv)--; \ LEAVESUB(multicall_cv); \ POPBLOCK(cx,PL_curpm); \ POPSTACK; \ CATCH_SET(multicall_oldcatch); \ LEAVE; \ SPAGAIN; \ } STMT_END #endif List-MoreUtils-0.33/sanexs.c0000644000175100017510000000022011616464330014326 0ustar adamadam#include "EXTERN.h" #include "perl.h" #include "XSUB.h" int main(int argc, char **argv) { return 0; } int boot_sanexs() { return 1; }