GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
Tie::Hash::Regex(3) User Contributed Perl Documentation Tie::Hash::Regex(3)

Tie::Hash::Regex - Match hash keys using Regular Expressions

  use Tie::Hash::Regex;
  my %h;

  tie %h, 'Tie::Hash::Regex';

  $h{key}   = 'value';
  $h{key2}  = 'another value';
  $h{stuff} = 'something else';

  print $h{key};  # prints 'value'
  print $h{2};    # prints 'another value'
  print $h{'^s'}; # prints 'something else'

  print tied(%h)->FETCH('k'); # prints 'value' and 'another value'

  delete $h{k};   # deletes $h{key} and $h{key2};

or (new! improved!)

  my %h : Regex;

Someone asked on Perlmonks if a hash could do fuzzy matches on keys - this is the result.

If there's no exact match on the key that you pass to the hash, then the key is treated as a regex and the first matching key is returned. You can force it to leap straight into the regex checking by passing a qr'ed regex into the hash like this:

  my $val = $h{qr/key/};

"exists" and "delete" also do regex matching. In the case of "delete" all values matching your regex key will be deleted from the hash.

One slightly strange thing. Obviously if you give a hash a regex key, then it's possible that more than one key will match (consider $h{qw/./}). It might be nice to be able to do stuff like:

  my @vals = $h{$pat};

to get all matching values back. Unfortuately, Perl knows that a given hash key can only ever return one value and so forces scalar context on the "FETCH" call when using the tied interface. You can get round this using the slightly less readable:

  my @vals = tied(%h)->FETCH($pat);

From version 0.06, you can use attributes to define your hash as being tied to Tie::Hash::Regex. You'll need to install the module Attribute::Handlers. Simply declare your hash using the attribute syntax:

    my %hash :Regex;

Get a value from the hash. If there isn't an exact match try a regex match.

See if a key exists in the hash. If there isn't an exact match try a regex match.

Delete a key from the hash. If there isn't an exact match try a regex match.

Dave Cross <dave@mag-sol.com>

Thanks to the Perlmonks <http://www.perlmonks.org> for the original idea and to Jeff "japhy" Pinyan for some useful code suggestions.

Copyright (C) 2001-8, Magnum Solutions Ltd. All Rights Reserved.

This script is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

perl(1).

perltie(1).

Tie::RegexpHash(1)

2021-01-25 perl v5.32.1

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.