Tie::RegexpHash - Use regular expressions as hash keys
Tie::RegexpHash is written for and tested on Perl 5.6.0, but should run with Perl 5.005. (Because it uses Regexp variables it cannot run on earlier versions of Perl.)
It uses only standard modules.
Installation is pretty standard:
perl Makefile.PL make make test make install
use Tie::RegexpHash; my %hash; tie %hash, 'Tie::RegexpHash'; $hash{ qr/^5(\s+|-)?gal(\.|lons?)?/i } = '5-GAL'; $hash{'5 gal'}; # returns "5-GAL" $hash{'5GAL'}; # returns "5-GAL" $hash{'5 gallon'}; # also returns "5-GAL" my $rehash = Tie::RegexpHash->new(); $rehash->add( qr/\d+(\.\d+)?/, "contains a number" ); $rehash->add( qr/s$/, "ends with an \`s\'" ); $rehash->match( "foo 123" ); # returns "contains a number" $rehash->match( "examples" ); # returns "ends with an `s'"
This module allows one to use regular expressions for hash keys, so that values can be associated with anything that matches the key.
Hashes can be operated on using the standard tied hash interface in Perl, or using an object-orineted interface described below.
my $obj = Tie::RegexpHash->new()
Creates a new "RegexpHash" (Regular Expression Hash) object.
$obj->add( $key, $value );
Adds a new key/value pair to the hash. $key can be a Regexp or a string (which is compiled into a Regexp).
If $key is already defined, the value will be changed. If $key matches an existing key (but is not the same), a warning will be shown if warnings are enabled.
$key
$value = $obj->match( $quasikey );
Returns the value associated with $quasikey. ($quasikey can be a string which matches an existing Regexp or an actual Regexp.) Returns 'undef' if there is no match.
Regexps are matched in the order they are defined.
if ($obj->match_exists( $quasikey )) ...
Returns a true value if there exists a matching key.
$value = $obj->remove( $quasikey );
Deletes the key associated with $quasikey. If $quasikey matches an existing key (but is not the same), a warning will be shown.
Returns the value associated with the key.
$obj->clear();
Removes all key/value pairs.
Robert Rothenberg <rrwo@cpan.org>
Simon Hanmer <sch@scubaplus.co.uk> & Bart Vetters <robartes@nirya.eb> for pointing out a bug in the logic of the _find() routine in v0.10
Tie::Hash::Regex is a module with a complimentary function. Rather than a hash with Regexps as keys that match a fetch, this module has standard keys but uses Regexps for fetches.
Copyright (c) 2001-2002 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Tie::RegexpHash, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Tie::RegexpHash
CPAN shell
perl -MCPAN -e shell install Tie::RegexpHash
For more information on module installation, please visit the detailed CPAN module installation guide.