String-Tokenizer-0.06000755000765000024 012663154514 14450 5ustar00stevanstaff000000000000README100644000765000024 135112663154514 15411 0ustar00stevanstaff000000000000String-Tokenizer-0.06 README for Perl module String::Tokenizer This module provides a simple string tokenizer which takes a string and splits it on whitespace. It also optionally takes a string of characters to use as delimiters, and returns them with the token set as well. This allows for splitting the string in many different ways. You can read a nicely formatted version of the documentation for this module online: https://metacpan.org/pod/String::Tokenizer You should be able to install this using your usual method for installing modules from CPAN. If you don't have one, have a look at: http://www.cpan.org/modules/INSTALL.html This module was written by Stevan Little Copyright (c) 2004-2016 Infinity Interactive, Inc. Changes100644000765000024 262112663154514 16025 0ustar00stevanstaff000000000000String-Tokenizer-0.06Revision history for Perl module String::Tokenizer 0.06 2016-02-23 - Tweaked format of this file closer to CPAN::Changes::Spec - Switched to Dist::Zilla, adding the github repo to the metadata, ensuring dist has META.{json,yml}, and min perl version specified. - Changed tests t/pod.t and t/pod_coverage.t to be release tests - Applied spelling corrections from RT#70040; thanks to BJ Webb. - Made the module names in SEE ALSO be L<...> links 0.05 2004-08-31 STEVAN - added support for whitespace tokens, feature requested by Stephan Tobias. - added tests for this - added documenation for this - fixed bug where the '0' token got ignored, also thanks to Stephan Tobias for this. 0.04 2004-08-22 STEVAN - added skipTokensUntil and collectTokensUntil methods to the String::Tokenizer::Iterator - added test for this - added documentation for this - added the pod.t and pod_coverage.t test files 0.03 2004-05-06 STEVAN - fixed some documentation issues. - added token iteration support with the inner class String::Tokenizer::Iterator. - added tests for iteration - added documentation for iteration 0.02 2004-04-12 STEVAN - error in the Makefile.PL file, no changes on this release 0.01 2004-04-12 STEVAN - original version; created by h2xs 1.22 with options -X -n String::Tokenizer LICENSE100644000765000024 4372712663154514 15573 0ustar00stevanstaff000000000000String-Tokenizer-0.06This software is copyright (c) 2004 by Infinity Interactive, Inc.. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system 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 GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2004 by Infinity Interactive, Inc.. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our 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. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, 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 a 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 tell them 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. 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 Agreement 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 work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 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 General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual 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 General Public License. d) 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. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 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 Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying 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. 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. 7. 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 the 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 the license, you may choose any version ever published by the Free Software Foundation. 8. 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 9. 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. 10. 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 Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2004 by Infinity Interactive, Inc.. This is free software, licensed under: The Artistic License 1.0 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 dist.ini100644000765000024 46112663154514 16156 0ustar00stevanstaff000000000000String-Tokenizer-0.06name = String-Tokenizer author = Stevan Little license = Perl_5 copyright_holder = Infinity Interactive, Inc. copyright_year = 2004 version = 0.06 [@Filter] -bundle = @Basic -remove = Readme [PkgVersion] [AutoPrereqs] [MetaJSON] [GithubMeta] [Git::Tag] tag_message= [Git::Push] META.yml100644000765000024 114512663154514 16003 0ustar00stevanstaff000000000000String-Tokenizer-0.06--- abstract: 'A simple string tokenizer.' author: - 'Stevan Little ' build_requires: Test::More: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.142060' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: String-Tokenizer requires: constant: '0' perl: '5.006' strict: '0' warnings: '0' resources: homepage: https://github.com/stevan/String-Tokenizer repository: https://github.com/stevan/String-Tokenizer.git version: '0.06' MANIFEST100644000765000024 43512663154514 15644 0ustar00stevanstaff000000000000String-Tokenizer-0.06# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.020. Changes LICENSE MANIFEST META.json META.yml Makefile.PL README dist.ini lib/String/Tokenizer.pm t/10_String_Tokenizer_test.t t/20_String_Tokenizer_Iterator_test.t t/release-pod.t t/release-pod_coverage.t META.json100644000765000024 216312663154514 16154 0ustar00stevanstaff000000000000String-Tokenizer-0.06{ "abstract" : "A simple string tokenizer.", "author" : [ "Stevan Little " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.142060", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "String-Tokenizer", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "constant" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Test::More" : "0" } } }, "release_status" : "stable", "resources" : { "homepage" : "https://github.com/stevan/String-Tokenizer", "repository" : { "type" : "git", "url" : "https://github.com/stevan/String-Tokenizer.git", "web" : "https://github.com/stevan/String-Tokenizer" } }, "version" : "0.06" } Makefile.PL100644000765000024 211512663154514 16502 0ustar00stevanstaff000000000000String-Tokenizer-0.06 # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.020. use strict; use warnings; use 5.006; use ExtUtils::MakeMaker ; my %WriteMakefileArgs = ( "ABSTRACT" => "A simple string tokenizer.", "AUTHOR" => "Stevan Little ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "String-Tokenizer", "EXE_FILES" => [], "LICENSE" => "perl", "NAME" => "String::Tokenizer", "PREREQ_PM" => { "constant" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "Test::More" => 0 }, "VERSION" => "0.06", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Test::More" => 0, "constant" => 0, "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); t000755000765000024 012663154514 14634 5ustar00stevanstaff000000000000String-Tokenizer-0.06release-pod.t100644000765000024 51512663154514 17342 0ustar00stevanstaff000000000000String-Tokenizer-0.06/t#!/usr/bin/perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use strict; use warnings; use Test::More; eval "use Test::Pod 1.14"; plan skip_all => "Test::Pod 1.14 required for testing POD" if $@; all_pod_files_ok(); String000755000765000024 012663154514 16405 5ustar00stevanstaff000000000000String-Tokenizer-0.06/libTokenizer.pm100644000765000024 4154712663154514 21110 0ustar00stevanstaff000000000000String-Tokenizer-0.06/lib/String package String::Tokenizer; use 5.006; use strict; use warnings; our $VERSION = '0.06'; use constant RETAIN_WHITESPACE => 1; use constant IGNORE_WHITESPACE => 0; ### constructor sub new { my ($_class, @args) = @_; my $class = ref($_class) || $_class; my $string_tokenizer = { tokens => [], delimiter => undef, handle_whitespace => IGNORE_WHITESPACE }; bless($string_tokenizer, $class); $string_tokenizer->tokenize(@args) if @args; return $string_tokenizer; } ### methods sub setDelimiter { my ($self, $delimiter) = @_; my $delimiter_reg_exp = join "\|" => map { s/(\W)/\\$1/g; $_ } split // => $delimiter; $self->{delimiter} = qr/$delimiter_reg_exp/; } sub handleWhitespace { my ($self, $value) = @_; $self->{handle_whitespace} = $value; } sub tokenize { my ($self, $string, $delimiter, $handle_whitespace) = @_; # if we have a delimiter passed in then use it $self->setDelimiter($delimiter) if defined $delimiter; # if we are asking about whitespace then handle it $self->handleWhitespace($handle_whitespace) if defined $handle_whitespace; # if the two above are not handled, then the object will use # the values set already. # split everything by whitespace no matter what # (possible multiple occurances of white space too) my @tokens; if ($self->{handle_whitespace}) { @tokens = split /(\s+)/ => $string; } else { @tokens = split /\s+/ => $string; } if ($self->{delimiter}) { # create the delimiter reg-ex # escape all non-alpha-numeric # characters, just to be safe my $delimiter = $self->{delimiter}; # loop through the tokens @tokens = map { # if the token contains a delimiter then ... if (/$delimiter/) { my ($token, @_tokens); # split the token up into characters # and the loop through all the characters foreach my $char (split //) { # if the character is a delimiter if ($char =~ /^$delimiter$/) { # and we already have a token in the works if (defined($token) && $token =~ /^.*$/) { # add the token to the # temp tokens list push @_tokens => $token; } # and then push our delimiter character # onto the temp tokens list push @_tokens => $char; # now we need to undefine our token $token = undef; } # if the character is not a delimiter then else { # check to make sure the token is defined $token = "" unless defined $token; # and then add the chracter to it $token .= $char; } } # now push any remaining token onto # the temp tokens list push @_tokens => $token if defined $token; # and return tokens @_tokens; } # if our token does not have # the delimiter in it else { # just return it $_ } } @tokens; } $self->{tokens} = \@tokens; } sub getTokens { my ($self) = @_; return wantarray ? @{$self->{tokens}} : $self->{tokens}; } sub iterator { my ($self) = @_; # returns a copy of the array return String::Tokenizer::Iterator->new($self->{tokens}); } package String::Tokenizer::Iterator; use strict; use warnings; sub new { ((caller())[0] eq "String::Tokenizer") || die "Insufficient Access Priviledges : Only String::Tokenizer can create String::Tokenizer::Iterator instances"; my ($_class, $tokens) = @_; my $class = ref($_class) || $_class; my $iterator = { tokens => $tokens, index => 0 }; bless($iterator, $class); return $iterator; } sub reset { my ($self) = @_; $self->{index} = 0; } sub hasNextToken { my ($self) = @_; return ($self->{index} < scalar @{$self->{tokens}}) ? 1 : 0; } sub hasPrevToken { my ($self) = @_; return ($self->{index} > 0); } sub nextToken { my ($self) = @_; return undef if ($self->{index} >= scalar @{$self->{tokens}}); return $self->{tokens}->[$self->{index}++]; } sub prevToken { my ($self) = @_; return undef if ($self->{index} <= 0); return $self->{tokens}->[--$self->{index}]; } sub currentToken { my ($self) = @_; return $self->{tokens}->[$self->{index} - 1]; } sub lookAheadToken { my ($self) = @_; return undef if ( $self->{index} <= 0 || $self->{index} >= scalar @{$self->{tokens}}); return $self->{tokens}->[$self->{index}]; } sub collectTokensUntil { my ($self, $token_to_match) = @_; # if this matches our current token ... # then we just return nothing as there # is nothing to accumulate if ($self->lookAheadToken() eq $token_to_match) { # then just advance it one $self->nextToken(); # and return nothing return; } # if it doesnt match our current token then, ... my @collection; # store the index we start at my $old_index = $self->{index}; my $matched; # loop through the tokens while ($self->hasNextToken()) { my $token = $self->nextToken(); if ($token ne $token_to_match) { push @collection => $token; } else { $matched++; last; } } unless ($matched) { # reset back to where we started, and ... $self->{index} = $old_index; # and return nothing return; } # and return our collection return @collection; } sub skipTokensUntil { my ($self, $token_to_match) = @_; # if this matches our current token ... if ($self->lookAheadToken() eq $token_to_match) { # then just advance it one $self->nextToken(); # and return success return 1; } # if it doesnt match our current token then, ... # store the index we start at my $old_index = $self->{index}; # and loop through the tokens while ($self->hasNextToken()) { # return success if we match our token return 1 if ($self->nextToken() eq $token_to_match); } # otherwise we didnt match, and should # reset back to where we started, and ... $self->{index} = $old_index; # return failure return 0; } sub skipTokenIfWhitespace { my ($self) = @_; $self->{index}++ if $self->lookAheadToken() =~ /^\s+$/; } sub skipTokens { my ($self, $num_token_to_skip) = @_; $num_token_to_skip ||= 1; $self->{index} += $num_token_to_skip; } *skipToken = \&skipTokens; 1; __END__ =head1 NAME String::Tokenizer - A simple string tokenizer. =head1 SYNOPSIS use String::Tokenizer; # create the tokenizer and tokenize input my $tokenizer = String::Tokenizer->new("((5+5) * 10)", '+*()'); # create tokenizer my $tokenizer = String::Tokenizer->new(); # ... then tokenize the string $tokenizer->tokenize("((5 + 5) - 10)", '()'); # will print '(, (, 5, +, 5, ), -, 10, )' print join ", " => $tokenizer->getTokens(); # create tokenizer which retains whitespace my $st = String::Tokenizer->new( 'this is a test with, (significant) whitespace', ',()', String::Tokenizer->RETAIN_WHITESPACE ); # this will print: # 'this', ' ', 'is', ' ', 'a', ' ', 'test', ' ', 'with', ' ', '(', 'significant', ')', ' ', 'whitespace' print "'" . (join "', '" => $tokenizer->getTokens()) . "'"; # get a token iterator my $i = $tokenizer->iterator(); while ($i->hasNextToken()) { my $next = $i->nextToken(); # peek ahead at the next token my $look_ahead = $i->lookAheadToken(); # ... # skip the next 2 tokens $i->skipTokens(2); # ... # then backtrack 1 token my $previous = $i->prevToken(); # ... # get the current token my $current = $i->currentToken(); # ... } =head1 DESCRIPTION A simple string tokenizer which takes a string and splits it on whitespace. It also optionally takes a string of characters to use as delimiters, and returns them with the token set as well. This allows for splitting the string in many different ways. This is a very basic tokenizer, so more complex needs should be either addressed with a custom written tokenizer or post-processing of the output generated by this module. Basically, this will not fill everyone's needs, but it spans a gap between simple C and the other options that involve much larger and complex modules. Also note that this is not a lexical analyser. Many people confuse tokenization with lexical analysis. A tokenizer merely splits its input into specific chunks, a lexical analyzer classifies those chunks. Sometimes these two steps are combined, but not here. =head1 METHODS =over 4 =item B If you do not supply any parameters, nothing happens, the instance is just created. But if you do supply parameters, they are passed on to the C method and that method is run. For information about those arguments, see C below. =item B This can be used to set the delimiter string, this is used by C. =item B This can be used to set the whitespace handling. It accepts one of the two constant values C or C. =item B Takes a C<$string> to tokenize, and optionally a set of C<$delimiter> characters to facilitate the tokenization and the type of whitespace handling with C<$handle_whitespace>. The C<$string> parameter and the C<$handle_whitespace> parameter are pretty obvious, the C<$delimiter> parameter is not as transparent. C<$delimiter> is a string of characters, these characters are then separated into individual characters and are used to split the C<$string> with. So given this string: (5 + (100 * (20 - 35)) + 4) The C method without a C<$delimiter> parameter would return the following comma separated list of tokens: '(5', '+', '(100', '*', '(20', '-', '35))', '+', '4)' However, if you were to pass the following set of delimiters C<(, )> to C, you would get the following comma separated list of tokens: '(', '5', '+', '(', '100', '*', '(', '20', '-', '35', ')', ')', '+', '4', ')' We now can differentiate the parens from the numbers, and no globbing occurs. If you wanted to allow for optionally leaving out the whitespace in the expression, like this: (5+(100*(20-35))+4) as some languages do. Then you would give this delimiter C<+*-()> to arrive at the same result. If you decide that whitespace is significant in your string, then you need to specify that like this: my $st = String::Tokenizer->new( 'this is a test with, (significant) whitespace', ',()', String::Tokenizer->RETAIN_WHITESPACE ); A call to C on this instance would result in the following token set. 'this', ' ', 'is', ' ', 'a', ' ', 'test', ' ', 'with', ' ', '(', 'significant', ')', ' ', 'whitespace' All running whitespace is grouped together into a single token, we make no attempt to split it into its individual parts. =item B Simply returns the array of tokens. It returns an array-ref in scalar context. =item B Returns a B instance, see below for more details. =back =head1 INNER CLASS A B instance is returned from the B's C method and serves as yet another means of iterating through an array of tokens. The simplest way would be to call C and just manipulate the array yourself, or push the array into another object. However, iterating through a set of tokens tends to get messy when done manually. So here I have provided the B to address those common token processing idioms. It is basically a bi-directional iterator which can look ahead, skip and be reset to the beginning. B B is an inner class, which means that only B objects can create an instance of it. That said, if B's C method is called from outside of the B package, an exception is thrown. =over 4 =item B This accepts an array reference of tokens and sets up the iterator. This method can only be called from within the B package, otherwise an exception will be thrown. =item B This will reset the internal counter, bringing it back to the beginning of the token list. =item B This will return true (1) if there are more tokens to be iterated over, and false (0) otherwise. =item B This will return true (1) if the beginning of the token list has been reached, and false (0) otherwise. =item B This dispenses the next available token, and move the internal counter ahead by one. =item B This dispenses the previous token, and moves the internal counter back by one. =item B This returns the current token, which will match the last token retrieved by C. =item B This peeks ahead one token to the next one in the list. This item will match the next item dispensed with C. This is a non-destructive look ahead, meaning it does not alter the position of the internal counter. =item B This will jump the internal counter ahead by 1. =item B This will jump the internal counter ahead by C<$number_to_skip>. =item B This will skip the next token if it is whitespace. =item B Given a string as a C<$token_to_match>, this will skip all tokens until it matches that string. If the C<$token_to_match> is never matched, then the iterator will return the internal pointer to its initial state. =item B Given a string as a C<$token_to_match>, this will collect all tokens until it matches that string, at which point the collected tokens will be returned. If the C<$token_to_match> is never matched, then the iterator will return the internal pointer to its initial state and no tokens will be returned. =back =head1 TO DO =over 4 =item I The Java StringTokenizer class allows for a token to be tokenized further, therefore breaking it up more and including the results into the current token stream. I have never used this feature in this class, but I can see where it might be a useful one. This may be in the next release if it works out. Possibly compliment this expansion with compression as well, so for instance double quoted strings could be compressed into a single token. =item I Allow for the creation of "token bookmarks". Meaning we could tag a specific token with a label, that index could be returned to from any point in the token stream. We could mix this with a memory stack as well, so that we would have an ordering to the bookmarks as well. =back =head1 BUGS None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it. =head1 CODE COVERAGE I use B to test the code coverage of my tests, below is the B report on this module's test suite. ------------------------ ------ ------ ------ ------ ------ ------ ------ File stmt branch cond sub pod time total ------------------------ ------ ------ ------ ------ ------ ------ ------ String/Tokenizer.pm 100.0 100.0 64.3 100.0 100.0 100.0 97.6 ------------------------ ------ ------ ------ ------ ------ ------ ------ Total 100.0 100.0 64.3 100.0 100.0 100.0 97.6 ------------------------ ------ ------ ------ ------ ------ ------ ------ =head1 SEE ALSO The interface and workings of this module are based largely on the StringTokenizer class from the Java standard library. Below is a short list of other modules that might be considered similar to this one. If this module does not suit your needs, you might look at one of these. =over 4 =item L Along with being a tokenizer, it also provides a means of moving through the resulting tokens, allowing for skipping of tokens and such. It was last updated in 2011. =item L This one hasn't been touched since 2001, although it did get up to version 0.27. It looks to lean over more towards the parser side than a basic tokenizer. =item L This is both a lexical analyzer and a tokenizer. It also uses XS, where String::Tokenizer is pure perl. This is something maybe to look into if you were to need a more beefy solution than String::Tokenizer provides. =back =head1 THANKS =over =item Thanks to Stephan Tobias for finding bugs and suggestions on whitespace handling. =back =head1 AUTHOR stevan little, Estevan@cpan.orgE =head1 COPYRIGHT AND LICENSE Copyright 2004-2016 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut release-pod_coverage.t100644000765000024 55512663154514 21221 0ustar00stevanstaff000000000000String-Tokenizer-0.06/t#!/usr/bin/perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use strict; use warnings; use Test::More; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; all_pod_coverage_ok(); 10_String_Tokenizer_test.t100644000765000024 565112663154514 22027 0ustar00stevanstaff000000000000String-Tokenizer-0.06/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 17; BEGIN { use_ok('String::Tokenizer') }; can_ok("String::Tokenizer", 'new'); { my $st = String::Tokenizer->new(); isa_ok($st, 'String::Tokenizer'); can_ok($st, 'tokenize'); can_ok($st, 'getTokens'); can_ok($st, 'iterator'); } # parse a nested expression my $STRING1 = "((5 + 10)-100) * (15 + (23 / 300))"; # expected output with no delimiters { my $st = String::Tokenizer->new(); isa_ok($st, 'String::Tokenizer'); $st->tokenize($STRING1); my @expected = qw{((5 + 10)-100) * (15 + (23 / 300))}; is_deeply( scalar $st->getTokens(), \@expected, '... this is the output we would expect'); } # expected output with () as delimiters { my $st = String::Tokenizer->new(); isa_ok($st, 'String::Tokenizer'); $st->tokenize($STRING1, '()'); my @expected = qw{( ( 5 + 10 ) -100 ) * ( 15 + ( 23 / 300 ) )}; is_deeply( [ $st->getTokens() ], \@expected, '... this is the output we would expect'); } # expected output with ()+-*/ as delimiters { my $st = String::Tokenizer->new($STRING1, '()=-*/'); isa_ok($st, 'String::Tokenizer'); my @expected = qw{( ( 5 + 10 ) - 100 ) * ( 15 + ( 23 / 300 ) )}; is_deeply( scalar $st->getTokens(), \@expected, '... this is the output we would expect'); } # it can also parse reasonably well formated perl code my $STRING2 = <new($STRING2, '();{}'); isa_ok($st, 'String::Tokenizer'); my @expected = qw(sub test { my ( $arg ) = @_ ; if ( $arg == 10 ) { return 1 ; } return 0 ; }); is_deeply( scalar $st->getTokens(), \@expected, '... this is the output we would expect'); } # check keeping all whitespace { my $st = String::Tokenizer->new($STRING2, '();{}', String::Tokenizer->RETAIN_WHITESPACE); isa_ok($st, 'String::Tokenizer'); my @expected = ( 'sub', ' ', 'test', ' ', '{', "\n ", 'my', ' ', '(', '$arg', ')', ' ', '=', ' ', '@_', ';', "\n ", 'if', ' ', '(', '$arg', ' ', '==', ' ', '10', ')', '{', "\n ", 'return', ' ', '1', ';', "\n ", '}', "\n ", 'return', ' ', '0', ';', "\n", '}', "\n" ); is_deeply( scalar $st->getTokens(), \@expected, '... this is the output we would expect'); $st->handleWhitespace(String::Tokenizer->IGNORE_WHITESPACE); $st->tokenize($STRING2); my @expected2 = qw(sub test { my ( $arg ) = @_ ; if ( $arg == 10 ) { return 1 ; } return 0 ; }); is_deeply( scalar $st->getTokens(), \@expected2, '... this is the output we would expect after changing whitespace handling'); } 20_String_Tokenizer_Iterator_test.t100644000765000024 1267512663154514 23725 0ustar00stevanstaff000000000000String-Tokenizer-0.06/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 100; BEGIN { use_ok('String::Tokenizer') }; # first check that our inner class # cannot be called from outside eval { String::Tokenizer::Iterator->new(); }; like($@, qr/Insufficient Access Priviledges/, '... this should have died'); # it can also parse reasonably well formated perl code my $STRING = <new($STRING, '();{}'); isa_ok($st, "String::Tokenizer"); can_ok("String::Tokenizer::Iterator", 'new'); my $i = $st->iterator(); isa_ok($i, "String::Tokenizer::Iterator"); can_ok($i, 'reset'); can_ok($i, 'hasNextToken'); can_ok($i, 'hasPrevToken'); can_ok($i, 'nextToken'); can_ok($i, 'prevToken'); can_ok($i, 'currentToken'); can_ok($i, 'lookAheadToken'); can_ok($i, 'skipToken'); can_ok($i, 'skipTokens'); can_ok($i, 'skipTokensUntil'); can_ok($i, 'collectTokensUntil'); my @iterator_output; push @iterator_output => $i->nextToken() while $i->hasNextToken(); ok(!defined($i->nextToken()), '... this is undefined'); ok(!defined($i->lookAheadToken()), '... this is undefined'); is_deeply( \@iterator_output, \@expected, '... this is the output we would expect'); my @reverse_iterator_output; push @reverse_iterator_output => $i->prevToken() while $i->hasPrevToken(); ok(!defined($i->prevToken()), '... this is undefined'); ok(!defined($i->lookAheadToken()), '... this is undefined'); is_deeply( \@reverse_iterator_output, [ reverse @expected ], '... this is the output we would expect'); my $look_ahead; while ($i->hasNextToken()) { my $next = $i->nextToken(); my $current = $i->currentToken(); is($look_ahead, $next, '... our look ahead matches out next') if defined $look_ahead; is($current, $next, '... our current matches out next'); $look_ahead = $i->lookAheadToken(); } $i->reset(); my @expected5 = qw({ ( ) @_ if $arg 10 { 1 } 0 }); my @skip_output; $i->skipTokens(2); while ($i->hasNextToken()) { push @skip_output => $i->nextToken(); $i->skipToken(); } is_deeply( \@skip_output, \@expected5, '... this is the output we would expect'); # test the skipTokensUntil and collectTokensUntil function with a double quoted string { my $st = String::Tokenizer->new('this "is a good way" to "test a double quoted" string' , '"'); isa_ok($st, "String::Tokenizer"); my $i = $st->iterator(); isa_ok($i, "String::Tokenizer::Iterator"); is($i->nextToken(), 'this', '... got the right start token'); ok($i->skipTokensUntil('"'), '... this will successfully skip'); is($i->nextToken(), 'is', '... got the right token next expected'); ok($i->skipTokensUntil('"'), '... this will successfully skip'); is($i->nextToken(), 'to', '... got the right token next expected'); is($i->nextToken(), '"', '... got the right token next expected'); is_deeply( [ $i->collectTokensUntil('"') ], [ qw/test a double quoted/ ], '... got the collection we expected'); is($i->nextToken(), 'string', '... got the right token next expected'); } { my $st = String::Tokenizer->new('this "is a good way" to "test a double quoted" string' , '"'); isa_ok($st, "String::Tokenizer"); my $i = $st->iterator(); isa_ok($i, "String::Tokenizer::Iterator"); is($i->nextToken(), 'this', '... got the right start token'); ok(!$i->skipTokensUntil('?'), '... this will not successfully match and so not skip'); is_deeply( [ $i->collectTokensUntil('"') ], [ ], '... got the collection (or lack thereof) we expected'); is_deeply( [ $i->collectTokensUntil('"') ], [ qw/is a good way/ ], '... got the collection (or lack thereof) we expected'); is($i->nextToken(), 'to', '... got the right token next expected'); is_deeply( [ $i->collectTokensUntil('not found') ], [ ], '... got the collection (or lack thereof) we expected'); is($i->nextToken(), '"', '... got the right token next expected'); } { my $st = String::Tokenizer->new( 'this is "a good way" to "test a double quoted " string' , '"', String::Tokenizer->RETAIN_WHITESPACE ); isa_ok($st, "String::Tokenizer"); my $i = $st->iterator(); isa_ok($i, "String::Tokenizer::Iterator"); is($i->nextToken(), 'this', '... got the right start token'); $i->skipTokenIfWhitespace(); is($i->lookAheadToken(), 'is', '... got the right start token'); $i->skipTokenIfWhitespace(); is($i->nextToken(), 'is', '... got the right start token'); $i->skipTokenIfWhitespace(); is($i->nextToken(), '"', '... got the right start token'); is_deeply( [ $i->collectTokensUntil('"') ], [ "a", " ", "good", " ", "way" ], '... got the collection (or lack thereof) we expected'); is($i->lookAheadToken(), ' ', '... our next token is whitespace'); $i->skipTokenIfWhitespace(); is($i->nextToken(), 'to', '... got the right token next expected'); # this is enough for now, we dont need to test the rest of the string }