This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: Tie/NetAddr/IP, Next: Tie/NumRange, Prev: Tie/Multidim, Up: Module List Implements a Hash where the key is a subnet ******************************************* NAME ==== Tie::NetAddr::IP - Implements a Hash where the key is a subnet SYNOPSIS ======== use Tie::NetAddr::IP; my %WhereIs; tie %WhereIs, Tie::NetAddr::IP; $WhereIs{"10.0.10.0/24"} = "Lab, First Floor"; $WhereIs{"10.0.20.0/24"} = "Datacenter, Second Floor"; $WhereIs{"10.0.30.0/27"} = "Remote location"; $WhereIs{"0.0.0.0/0"} = "God knows where"; foreach $host ("10.0.10.1", "10.0.20.15", "10.0.32.17", "10.10.0.1") { print "Host $host is in ", $WhereIs{$host}, "\n"; } foreach $subnet (keys %WhereIs) { print "Network ", $subnet, " is used in ", $WhereIs{$subnet}, "\n"; } untie %WhereIs; DESCRIPTION =========== This module overloads hashes so that the key can be a subnet as in *NetAddr::IP*. When looking values up, an interpretation will be made to find the given key *within* the subnets specified in the hash. The code sample provided on the SYNOPSIS would print out the locations of every machine in the foreach loop. Care must be taken, as only strings that can be parsed as an IP address by *NetAddr::IP* can be used as keys for this hash. Iterators on the hash such as foreach, each, keys and values will only see the actual subnets provided as keys to the hash. When looking up a value such as in `$hash{$ipaddress}' this IP address will be looked up among the subnets existing as keys within the hash. The matching subnet with the longest mask (ie, the most specific subnet) will win and its associated value will be returned. This code can be distributed freely according to the terms set forth in the PERL license provided that proper credit is maintained. Please send bug reports and feedback to the author for further improvement. AUTHOR ====== Luis E. Munoz (lem@cantv.net) SEE ALSO ======== perl(1), NetAddr::IP(3).  File: pm.info, Node: Tie/NumRange, Next: Tie/OffsetArray, Prev: Tie/NetAddr/IP, Up: Module List Keeps a number within a range of values. **************************************** NAME ==== Tie::NumRange - Keeps a number within a range of values. SYNOPSIS ======== use Tie::NumRange; tie my($chr), Tie::NumRange => ( 100, # initial 0, # min 255, # max ); $chr *= 3; # $chr is 255 $chr = -5; # $chr is 0 tie my($positive), Tie::NumRange => ( 1, 1, undef ); $positive = 2**16; # ok $positive = 0; # $pos is 1 DESCRIPTION =========== This module institutes a range of values for a number. The lower and upper bounds can be unlimited by passing undef in their place. Constructor ----------- tie $number, Tie::NumRange => ($init, $min, $max); If `$min' is undef, the number has no lower bound. Likewise for `$max'. AUTHOR ====== Jeff "japhy" Pinyan CPAN ID: PINYAN japhy@pobox.com http://www.pobox.com/~japhy/  File: pm.info, Node: Tie/OffsetArray, Next: Tie/PerFH, Prev: Tie/NumRange, Up: Module List Tie one array to another, with index offset ******************************************* NAME ==== Tie::OffsetArray - Tie one array to another, with index offset SYNOPSIS ======== use Tie::OffsetArray; tie @a, 'Tie::OffsetArray', 1, \@b; # offset=1; use given array. tie @c, 'Tie::OffsetArray', 2; # use anonymous array. $a[0] = 'x'; # assign to $b[1]; tied(@a)->array->[0] = 'y'; # assign to $b[0]. DESCRIPTION =========== When tied to this class, an array's behavior is completely normal. For its internal storage, it uses another array, either one supplied by the caller, or a new anonymous one. Accesses to the tied array are mapped down to the storage array by offsetting the index by some constant amount. A special method on the tied object returns a reference to the storage array, so that the elements below the offset can be accessed. This is particularly useful if the storage array was not supplied by the caller. AUTHOR ====== jdporter@min.net (John Porter) COPYRIGHT ========= This is free software. This software may be modified and distributed under the same terms as Perl itself.  File: pm.info, Node: Tie/PerFH, Next: Tie/Persistent, Prev: Tie/OffsetArray, Up: Module List creates scalars specific to a filehandle **************************************** NAME ==== Tie::PerFH - creates scalars specific to a filehandle SYNOPSIS ======== use Tie::PerFH; use strict; tie my($font), 'Tie::PerFH'; # $font is 'blue' when STDOUT is select()ed $font = "blue"; select OTHER_FH; # $font is 'red' when OTHER_FH is select()ed $font = "red"; DESCRIPTION =========== This module creates scalars that hold different values depending on which filehandle is selected (much like the format variables, and the autoflush variable). AUTHOR ====== Jeff "japhy" Pinyan CPAN ID: PINYAN japhy@pobox.com http://www.pobox.com/~japhy/  File: pm.info, Node: Tie/Persistent, Next: Tie/Pick, Prev: Tie/PerFH, Up: Module List persistent data structures via tie ********************************** NAME ==== Tie::Persistent - persistent data structures via tie SYNOPSIS ======== use Tie::Persistent; tie %DB, 'Tie::Persistent', 'file', 'rw'; # read data from 'file' # now create/add/modify database ... untie %DB; # stores data back into 'file' tie %ReadOnly, 'Tie::Persistent', 'file'; foreach (keys %ReadOnly) { print "$_ => $ReadOnly{$_}\n"; } DESCRIPTION =========== The Persistent package makes working with persistent data real easy by using the tie interface. It works by storing data contained in a variable into a file (not unlike a database). The primary advantage is speed, as the whole datastructure is kept in memory (which is also a limitation), and, of course, that you can use arbitrary data structures inside the variable (unlike DB_File). If you want to make an arbitrary object persistent, just store its ref in a scalar tied to 'Tie::Persistent'. *Beware*: not every data structure or object can be made persistent. For example, it may not contain GLOB or CODE refs, as these are not really dumpable (yet?). Also, it works only for variables, you cannot use it for file handles. [A persistent file handle? Hmmm... Hmmm! Let me think about it. I have a vague idea, I'll have to do some unconscious work on...] PARAMETERS ========== tie %Hash, 'Tie::Persistent', file, mode, *other...*; tie @Array, 'Tie::Persistent', file, mode, *other...*; tie $Scalar, 'Tie::Persistent', file, mode, *other...*; file Filename to store the data in. No naming convention is enforced, but I personally use the suffix 'pdb' for "Perl Data Base" (or "Persistent Data Base"?). No file locking is done; see the section on locking below. mode (optional) Same as mode for POSIX fopen() or IO::File::open. Basically a combination of 'r', 'w', 'a' and '+'. Semantics: 'r' .... read only. Modifications in the data are not stored back into the file. A non-existing file gives an error. This is the default if no mode is given. 'rw' ... read/write. Modifications are stored back, if the file does not exist, it is created. 'w' .... write only. The file is not read, the variable starts out empty. 'a', '+' ... append. Same as 'w', but creates numbered backup files. 'ra', 'r+' ... Same as 'rw', but creates numbered backup files. When some kind of write access is specified, a backup file of the old dataset is always created. [You'll thank me for that, believe me.] The reason is simple: when you tie a variable read-write (the contents get restored from the file), and your program isn't fully debugged yet, it may die in the middle of some modifications, but the data will still be written back to the file, possibly leaving them inconsistent. Then you always have at least the previous version that you can restore from. The default backup filenames follow the Emacs notation, i.e. a '~' is appended; for numbered backup files (specified as 'a' or '+'), an additional number and a '~' is appended. For a file 'data.pdb', the normal backup file would be 'data.pdb~' and the numbered backup files would be 'data.pdb~1~', 'data.pdb~2~' and so on. The latest backup file is the one with the highest number. The backup filename format can be overridden, see below. other (optional, experimental) This can be a reference to another (possibly tied) variable or a name of another tieable package. If a ref is given, it is used internally to store the variable data instead of an anonymous variable ref. This allows to make other tied datastructures persistent, e.g. you could first tie a hash to Tie::IxHash to make it order-preserving and then give it to Tie::Persistent to make it persistent. A plain name is used to create this tied variable internally. Trailing arguments are passed to the other tieable package. Example: tie %h, 'Tie::Persistent', 'file', 'rw', 'Tie::IxHash'; or tie %ixh, 'Tie::IxHash'; tie %ph, 'Tie::Persistent', 'file', 'w', \%ixh; # you can now use %ixh as an alias for %ph NOTE: This is an experimental feature. It may or may not work with other Tie:: packages. I have only tested it with 'Tie::IxHash'. Please report success or failure. LOCKING ======= The data file is not automatically locked. Locking has to be done outside of the package. I recommend using a module like 'Lockfile::Simple' for that. There are typical two scenarios for locking: you either lock just the 'tie' and/or 'untie' calls, but not the data manipulation, or you lock the whole 'tie' - modify data - 'untie' sequence. CONFIGURATION VARIABLES ======================= *`$Tie::Persistent::Readable'* controls which format to use to store the data inside the file. 'false' means to use 'Storable', which is faster (and the default), 'true' means to use 'Data::Dumper', which is slower but much more readable and thus meant for debugging. This only influences the way the datastructure is *written*, format detection on read is automatic. *`$Tie::Persistent::BackupFile'* points to a sub that determines the backup filename format. It gets the filename as $_[0] and returns the backup filename. The default is sub { "$_[0]~"; } which is the Emacs backup format. For NT, you might want to change this to sub { "$_[0].bak"; } or something. *`$Tie::Persistent::NumberedBackupFile'* points to a sub that determines the numbered backup filename format. It gets the filename and a number as $_[0] and $_[1] respectively and returns the backup filename. The default is sub { "$_[0]~$_[1]~"; } which is the extended Emacs backup format. NOTES ===== There is a module called 'Class::Eroot' that intends to do the same thing but uses a more difficult interface (and also is rather old, not that this is a bad thing per se), so I think my module could be of some use. 'Tie::Persistent' uses 'Storable' and 'Data::Dumper' internally, so these must be installed. For testing, I use 'Tie::IxHash', but 'make test' still does some tests if it is not installed. BUGS ==== Numbered backupfile creation might have problems if the filename contains the first six digits of the speed of light (in m/s). All other bugs, please tell me! AUTHOR ====== Roland Giersig COPYRIGHT ========= Copyright (c) 1999 Roland Giersig. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. SEE ALSO ======== *Note Storable: Storable,, *Note Data/Dumper: Data/Dumper,.  File: pm.info, Node: Tie/Pick, Next: Tie/RDBM, Prev: Tie/Persistent, Up: Module List Randomly pick (and remove) an element from a set. ************************************************* NAME ==== Tie::Pick - Randomly pick (and remove) an element from a set. SYNOPSIS ======== use Tie::Pick; tie my $beatle => Tie::Pick => qw /Paul Ringo George John/; print "My favourite beatles are $beatle and $beatle.\n"; # Prints: My favourite beatles are John and Ringo. DESCRIPTION =========== `Tie::Pick' lets you randomly pick an element from a set, and have that element removed from the set. The set to pick from is given as an list of extra parameters on tieing the scalar. If the set is exhausted, the scalar will have the undefined value. A new set to pick from can be given by assigning a reference to an array of the values of the set to the scalar. The algorithm used for picking values of the set is a variant of the Fisher-Yates algorithm, as discussed in Knuth [3]. It was first published by Fisher and Yates [2], and later by Durstenfeld [1]. The difference is that we only perform one iteration on each look up. If you want to pick elements from a set, without removing the element after picking it, see the `Tie::Select' module. CAVEAT ====== Salfi [4] points to a big caveat. If the outcome of a random generator is solely based on the value of the previous outcome, like a linear congruential method, then the outcome of a shuffle depends on exactly three things: the shuffling algorithm, the input and the seed of the random generator. Hence, for a given list and a given algorithm, the outcome of the shuffle is purely based on the seed. Many modern computers have 32 bit random numbers, hence a 32 bit seed. Hence, there are at most 2^32 possible shuffles of a list, foreach of the possible algorithms. But for a list of n elements, there are n! possible permutations. Which means that a shuffle of a list of 13 elements will not generate certain permutations, as 13! > 2^32. REFERENCES ========== [1] R. Durstenfeld: *CACM*, 7, 1964. pp 420. [2] R. A. Fisher and F. Yates: *Statistical Tables*. London, 1938. Example 12. [3] D. E. Knuth: *The Art of Computer Programming*, Volume 2, Third edition. Section 3.4.2, Algorithm P, pp 145. Reading: Addison-Wesley, 1997. ISBN: 0-201-89684-2. [4] R. Salfi: *COMPSTAT 1974*. Vienna: 1974, pp 28 - 35. REVISION HISTORY ================ $Log: Pick.pm,v $ Revision 1.1 1999/07/20 06:55:25 abigail Initial revision AUTHOR ====== This package was written by Abigail. COPYRIGHT and LICENSE ===================== This package is copyright 1999 by Abigail. This program is free and open software. You may use, copy, modify, distribute and sell this program (and any modified variants) in any way you wish, provided you do not restrict others to do the same.  File: pm.info, Node: Tie/RDBM, Next: Tie/RangeHash, Prev: Tie/Pick, Up: Module List Tie hashes to relational databases ********************************** NAME ==== Tie::RDBM - Tie hashes to relational databases SYNOPSIS ======== use Tie::RDBM; tie %h,Tie::RDBM,'mysql:test',{table=>'Demo',create=>1,autocommit=>0}; $h{'key1'} = 'Some data here'; $h{'key2'} = 42; $h{'key3'} = { complex=>['data','structure','here'],works=>'true' }; $h{'key4'} = new Foobar('Objects work too'); print $h{'key3'}->{complex}->[0]; tied(%h)->commit; untie %h; DESCRIPTION =========== This module allows you to tie Perl associative arrays (hashes) to SQL databases using the DBI interface. The tied hash is associated with a table in a local or networked database. One field of the table becomes the hash key, and another becomes the value. Once tied, all the standard hash operations work, including iteration over keys and values. If you have the Storable module installed, you may store arbitrarily complex Perl structures (including objects) into the hash and later retrieve them. When used in conjunction with a network-accessible database, this provides a simple way to transmit data structures between Perl programs on two different machines. TIEING A DATABASE ================= tie %VARIABLE,Tie::RDBM,DSN [,\%OPTIONS] You tie a variable to a database by providing the variable name, the tie interface (always "Tie::RDBM"), the data source name, and an optional hash reference containing various options to be passed to the module and the underlying database driver. The data source may be a valid DBI-style data source string of the form "dbi:driver:database_name[:other information]", or a previously-opened database handle. See the documentation for DBI and your DBD driver for details. Because the initial "dbi" is always present in the data source, Tie::RDBM will automatically add it for you. The options array contains a set of option/value pairs. If not provided, defaults are assumed. The options are: user ["] Account name to use for database authentication, if necessary. Default is an empty string (no authentication necessary). password ["] Password to use for database authentication, if necessary. Default is an empty string (no authentication necessary). db ["] The data source, if not provided in the argument. This allows an alternative calling style: tie(%h,Tie::RDBM,{db=>'dbi:mysql:test',create=>1}; table ['pdata'] The name of the table in which the hash key/value pairs will be stored. key ['pkey'] The name of the column in which the hash key will be found. If not provided, defaults to "pkey". value ['pvalue'] The name of the column in which the hash value will be found. If not provided, defaults to "pvalue". frozen ['pfrozen'] The name of the column that stores the boolean information indicating that a complex data structure has been "frozen" using Storable's freeze() function. If not provided, defaults to "pfrozen". NOTE: if this field is not present in the database table, or if the database is incapable of storing binary structures, Storable features will be disabled. create [0] If set to a true value, allows the module to create the database table if it does not already exist. The module emits a CREATE TABLE command and gives the key, value and frozen fields the data types most appropriate for the database driver (from a lookup table maintained in a package global, see DATATYPES below). The success of table creation depends on whether you have table create access for the database. The default is not to create a table. tie() will fail with a fatal error. drop [0] If the indicated database table exists, but does not have the required key and value fields, Tie::RDBM can try to add the required fields to the table. Currently it does this by the drastic expedient of DROPPING the table entirely and creating a new empty one. If the drop option is set to true, Tie::RDBM will perform this radical restructuring. Otherwise tie() will fail with a fatal error. "drop" implies "create". This option defaults to false. A future version of Tie::RDBM may implement a last radical restructuring method; differences in DBI drivers and database capabilities make this task harder than it would seem. autocommit [1] If set to a true value, the "autocommit" option causes the database driver to commit after every store statement. If set to a false value, this option will not commit to the database until you explicitly call the Tie::RDBM commit() method. The autocommit option defaults to true. DEBUG [0] When the "DEBUG" option is set to a true value the module will echo the contents of SQL statements and other debugging information to standard error. USING THE TIED ARRAY ==================== The standard fetch, store, keys(), values() and each() functions will work as expected on the tied array. In addition, the following methods are available on the underlying object, which you can obtain with the standard tie() operator: commit() (tied %h)->commit(); When using a database with the autocommit option turned off, values that are stored into the hash will not become permanent until commit() is called. Otherwise they are lost when the application terminates or the hash is untied. Some SQL databases don't support transactions, in which case you will see a warning message if you attempt to use this function. rollback() (tied %h)->rollback(); When using a database with the autocommit option turned off, this function will roll back changes to the database to the state they were in at the last commit(). This function has no effect on database that don't support transactions. DATABASES AND DATATYPES ======================= Perl is a weakly typed language. Databases are strongly typed. When translating from databases to Perl there is inevitably some data type conversion that you must worry about. I have tried to keep the details as transparent as possible without sacrificing power; this section discusses the tradeoffs. If you wish to tie a hash to a preexisting database, specify the database name, the table within the database, and the fields you wish to use for the keys and values. These fields can be of any type that you choose, but the data type will limit what can be stored there. For example, if the key field is of type "int", then any numeric value will be a valid key, but an attempt to use a string as a key will result in a run time error. If a key or value is too long to fit into the data field, it will be truncated silently. For performance reasons, the key field should be a primary key, or at least an indexed field. It should also be unique. If a key is present more than once in a table, an attempt to fetch it will return the first record found by the SQL select statement. If you wish to store Perl references in the database, the module needs an additional field in which it can store a flag indicating whether the data value is a simple or a complex type. This "frozen" field is treated as a boolean value. A "tinyint" data type is recommended, but strings types will work as well. In a future version of this module, the "frozen" field may be turned into a general "datatype" field in order to minimize storage. For future compatability, please use an integer for the frozen field. If you use the "create" and/or "drop" options, the module will automatically attempt to create a table for its own use in the database if a suitable one isn't found. It uses information defined in the package variable %Tie::RDBM::Types to determine what kind of data types to create. This variable is indexed by database driver. Each index contains a four-element array indicating what data type to use for each of the key, value and frozen fields, and whether the database can support binary types. Since I have access to only a limited number of databases, the table is currently short: Driver Key Field Value Field Frozen Field Binary? mysq varchar(127) longblob tinyint 1 mSQL char(255) char(255) int 0 Sybase varchar(255) varbinary(255) tinyint 1 default varchar(255) varbinary(255) tinyint 1 The "default" entry is used for any driver not specifically mentioned. You are free to add your own entries to this table, or make corrections. Please send me e-mail with any revisions you make so that I can share the wisdom. STORABLE CAVEATS ================ Because the Storable module packs Perl structures in a binary format, only those databases that support a "varbinary" or "blob" type can handle complex datatypes. Furthermore, some databases have strict limitations on the size of these structures. For example, SyBase and MS SQL Server have a "varbinary" type that maxes out at 255 bytes. For structures larger than this, the databases provide an "image" type in which storage is allocated in 2K chunks! Worse, access to this image type uses a non-standard SQL extension that is not supported by DBI. Databases that do not support binary fields cannot use the Storable feature. If you attempt to store a reference to a complex data type in one of these databases it will be converted into strings like "HASH(0x8222cf4)", just as it would be if you tried the same trick with a conventional tied DBM hash. If the database supports binary fields of restricted length, large structures may be silently truncated. Caveat emptor. It's also important to realize the limitations of the Storable mechanism. You can store and retrieve entire data structures, but you can't twiddle with individual substructures and expect them to persist when the process exits. To update a data structure, you must fetch it from the hash, make the desired modifications, then store it back into the hash, as the example below shows: *Process #1:* tie %h,Tie::RDBM,'mysql:Employees:host.somewhere.com', {table=>'employee',user=>'fred',password=>'xyzzy'}; $h{'Anne'} = { office=>'999 Infinity Drive, Rm 203', age => 29, salary => 32100 }; $h{'Mark'} = { office=>'000 Iteration Circle, Rm -123', age => 32, salary => 35000 }; *Process #2:* tie %i,Tie::RDBM,'mysql:Employees:host.somewhere.com', {table=>'employee',user=>'george',password=>'kumquat2'}; foreach (keys %i) { $info = $i{$_}; if ($info->{age} > 30) { # Give the oldies a $1000 raise $info->{salary} += 1000; $i{$_} = $info; } } This example also demonstrates how two Perl scripts running on different machines can use Tie::RDBM to share complex data structures (in this case, the employee record) without resorting to sockets, remote procedure calls, shared memory, or other gadgets PERFORMANCE =========== What is the performance hit when you use this module? It can be significant. I used a simple benchmark in which Perl parsed a 6180 word text file into individual words and stored them into a database, incrementing the word count with each store. The benchmark then read out the words and their counts in an each() loop. The database driver was mySQL, running on a 133 MHz Pentium laptop with Linux 2.0.30. I compared Tie::RDBM, to DB_File, and to the same task using vanilla DBI SQL statements. The results are shown below: STORE EACH() LOOP Tie::RDBM 28 s 2.7 s Vanilla DBI 15 s 2.0 s DB_File 3 s 1.08 s During stores, there is an approximately 2X penalty compared to straight DBI, and a 15X penalty over using DB_File databases. For the each() loop (which is dominated by reads), the performance is 2-3 times worse than DB_File and much worse than a vanilla SQL statement. I have not investigated the bottlenecks. TO DO LIST ========== - Store strings, numbers and data structures in separate fields for space and performance efficiency. - Expand data types table to other database engines. - Catch internal changes to data structures and write them into database automatically. BUGS ==== Yes. AUTHOR ====== Lincoln Stein, lstein@w3.org COPYRIGHT ========= Copyright (c) 1998, Lincoln D. Stein This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AVAILABILITY ============ The latest version can be obtained from: http://www.genome.wi.mit.edu/~lstein/Tie-DBM/ SEE ALSO ======== perl(1), DBI(3), Storable(3)  File: pm.info, Node: Tie/RangeHash, Next: Tie/RefHash, Prev: Tie/RDBM, Up: Module List Implements "range hashes" in Perl ********************************* NAME ==== Tie::RangeHash - Implements "range hashes" in Perl REQUIREMENTS ============ `Tie::RangeHash' is written for Perl 5.005_62 or 5.6.0 and tested on the latter. It should work in Perl 5.005, although I have not tested it. It uses the following modules: Carp Tie::Hash The test suite will use `Time::HiRes' if it is available. Installation ------------ Installation is pretty standard: perl Makefile.PL make make test make install SYNOPSIS ======== use Tie::RangeHash; tie %hash, Tie::RangeHash; $hash{'A,C'} = 1; $hash{'D,F'} = 2; $hash{'G,K'} = 3; $hash{'E'}; # returns '2' $hash{'BB'}; # returns '1' $hash{'KL'}; # returns nothing ('undef') DESCRIPTION =========== This module allows hashes to associate a value with a range of keys rather than a single key. For example, you could pass date ranges to the hash and then query it with a specific date, like so: $cost{'1999-12-15,2000-01-14'} = 150; $cost{'2000-01-15,2000-02-14'} = 103; $cost{'2000-02-15,2000-03-14'} = 97; and then query the cost on a specific date: $this_cost = $cost{'2000-02-08'}; Numeric key ranges can also be used: tie %hash, 'Tie::RangeHash', { Type => Tie::RangeHash::TYPE_NUMBER }; $hash{'1.4,1.8'} = 'Jim'; $hash{'1.0,1.399999'} = 'Ned'; $hash{'1.800001,2.0'} = 'Boo'; If string or numeric comparisons are not appropriate for the keys you need, a custom comparison routine can be specified: sub reverse_compare { my ($A, $B) = @_; return ($B cmp $A); } tie %hash, 'Tie::RangeHash', { Comparison => \&reverse_compare }; The comparison routine should work the same as custom sort subroutines do (A < B returns -1, A=B returns 0, A > B returns 1). Your keys must also be representable as a string (a future version of this module may add filters to overcome that limitation). If you need to define your own separator, you can do so: tie %hash, 'Tie::RangeHash', { Separator => '..' }; or tie %hash, 'Tie::RangeHash', { Separator => qr/\s/ }; Note that if you define it as a regular expression, warnings and errors will use the default comma ',' separator (since there is no way to "reverse" a regular expression). Duplicate and overlapping ranges are not supported. Once a range is defined, it exists for the lifetime of the hash. (Future versions may allow you to change this behavior.) Warnings are now disabled by default unless you run Perl with the -W flag. In theory, you should also be able to say use warnings 'Tie::RangeHash'; but this does not always seem to work. (Apparently something is broken with warnings.) Internally, the hash is actually a binary tree. Values are retrieved by searching the tree for nodes that where the key is within range. CAVEATS ======= The binary-tree code is spontaneously written and has a very simple tree-banacing scheme. (It needs some kind of scheme since sorted data will produce a very lopsided tree which is no more efficient than an array.) It appears to work, but has not been fully tested. A future version of this module may use an improved binary-tree algorithm. Or it may use something else. This module is incomplete... It needs the FIRSTKEY, NEXTKEY, and (maybe) DESTROY methods. AUTHOR ====== Robert Rothenberg LICENSE ======= Copyright (c) 2000 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.  File: pm.info, Node: Tie/RefHash, Next: Tie/RegexpHash, Prev: Tie/RangeHash, Up: Module List use references as hash keys *************************** NAME ==== Tie::RefHash - use references as hash keys SYNOPSIS ======== require 5.004; use Tie::RefHash; tie HASHVARIABLE, 'Tie::RefHash', LIST; untie HASHVARIABLE; DESCRIPTION =========== This module provides the ability to use references as hash keys if you first tie the hash variable to this module. It is implemented using the standard perl TIEHASH interface. Please see the tie entry in perlfunc(1) and perltie(1) for more information. EXAMPLE ======= use Tie::RefHash; tie %h, 'Tie::RefHash'; $a = []; $b = {}; $c = \*main; $d = \"gunk"; $e = sub { 'foo' }; %h = ($a => 1, $b => 2, $c => 3, $d => 4, $e => 5); $a->[0] = 'foo'; $b->{foo} = 'bar'; for (keys %h) { print ref($_), "\n"; } AUTHOR ====== Gurusamy Sarathy gsar@activestate.com VERSION ======= Version 1.21 22 Jun 1999 SEE ALSO ======== perl(1), perlfunc(1), perltie(1)  File: pm.info, Node: Tie/RegexpHash, Next: Tie/STDERR, Prev: Tie/RefHash, Up: Module List Use regular expressions as hash keys ************************************ NAME ==== Tie::RegexpHash - Use regular expressions as hash keys REQUIREMENTS ============ `Tie::RegexpHash' is written for and tested on Perl 5.6.0. A future version might be tweaked to run on 5.005. It uses only standard modules. Installation ------------ Installation is pretty standard: perl Makefile.PL make make install No test suite is available in this version. SYNOPSIS ======== 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'" DESCRIPTION =========== 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. METHODS ======= new --- my $obj = Tie::RegexpHash->new() Creates a new "RegexpHash" (Regular Expression Hash) object. add --- $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. match ----- $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. match_exists ------------ if ($obj->match_exists( $quasikey )) ... Returns a true value if there exists a matching key. remove ------ $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 if warnings are enabled. Returns the value associated with the key. clear ----- $obj->clear(); Removes all key/value pairs. AUTHOR ====== Robert Rothenberg LICENSE ======= Copyright (c) 2001 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.  File: pm.info, Node: Tie/STDERR, Next: Tie/Scalar, Prev: Tie/RegexpHash, Up: Module List Send output of your STDERR to a process or mail *********************************************** NAME ==== Tie::STDERR - Send output of your STDERR to a process or mail SYNOPSIS ======== use Tie::STDERR; if (; use Tie::STDERR 'root'; use Tie::STDERR 'root', 'Errors in the script'; use Tie::STDERR '>> /tmp/log'; use Tie::STDERR '| mail -s Error root'; use Tie::STDERR \&func; use Tie::STDERR \$append_to_scalar; DESCRIPTION =========== Sends all output that would otherwise go to STDERR either by email to root or whoever is responsible, or to a file or a process, or calls your function at the end of the script. This way you can easily change the destination of your error messages from *inside* of your script. The mail will be sent or the system command or Perl function run only if there actually is some output detected - something like cron would do. The behaviour of the module is directed via the arguments to use, as shown above. If you do not give arguments, an e-mail to root is sent. You can give up to two scalars - name of the recipient and the subject of the email. Argument that starts with | will send the output to a process. If it starts with > or >>, it will be written (appended) to a file. If the argument is explicit undef, if will untie previous tieness. Reference to a functions registers a callback Perl function that will be passed the string of the data sent to STDERR during your script and reference to scalar registers scalar, to which this data will be appended. The module will catch all output, including your explicit prints to STDERR, warnings about undefined values, dies and even dies as a result of compilation error. You do not need any special treatment/functions - Tie::STDERR will catch all. However, if you run external command (system, "), stderr output from that process won't be caught. It is because we tie Perl's STDERR fileglob, not the external filehandle. This has the advantage that you can say { local *STDERR; untie *STDERR; print STDERR "Now we go directly to STDERR\n"; } My main goal was to provide a tool that could be used easily, especially (but not only) for CGI scripts. My assumption is that the CGI scripts should run without anything being sent to STDERR (and error_log, where it mixes up with other messages, even if you use CGI::Carp). We've found it usefull to get delivered the error and warning messages together with any relevant information (%ENV) via email. Under mod_perl/Apache::Registry, Tie::STDERR tries to work as with normal scripts - sends the message at the end of each request. This is done by registering a cleanup handler. If you use Tie::STDERR 'arguments'; in your scripts, everything is fine, because the new parameters are reset each time the script is run. However, if you use some home grown module like we do (CGI::BuildPage, wrapper around CGI) that uses Tie::STDERR, that use will only be called once, during the compilation of the module and the arguments are not reset and the cleanup handler will not be registered. So next time your Apache::Registry script uses this CGI::BuildPage or however you call it, you won't probably get receive the e-mail. The solution is to call explicitely function Tie::STDERR::register_apache_cleanup in your module - I've put it into the new method that is called in every reasonable script. (This is however subject to change. Let me know if you find better solution or if this explanation is unclear.) BUGS ==== The Tie::STDERR catches the compile time errors, but it doesn't get the reason, only the fact that there was an error. I do not know how to fix this. VERSION ======= 0.26 AUTHOR ====== (c) 1998 Jan Pazdziora, adelton@fi.muni.cz, http://www.fi.muni.cz/~adelton/ at Faculty of Informatics, Masaryk University in Brno, Czech Republic  File: pm.info, Node: Tie/Scalar, Next: Tie/Scalar/Timeout, Prev: Tie/STDERR, Up: Module List base class definitions for tied scalars *************************************** NAME ==== Tie::Scalar, Tie::StdScalar - base class definitions for tied scalars SYNOPSIS ======== package NewScalar; require Tie::Scalar; @ISA = (Tie::Scalar); sub FETCH { ... } # Provide a needed method sub TIESCALAR { ... } # Overrides inherited method package NewStdScalar; require Tie::Scalar; @ISA = (Tie::StdScalar); # All methods provided by default, so define only what needs be overridden sub FETCH { ... } package main; tie $new_scalar, 'NewScalar'; tie $new_std_scalar, 'NewStdScalar'; DESCRIPTION =========== This module provides some skeletal methods for scalar-tying classes. See *Note Perltie: (perl.info)perltie, for a list of the functions required in tying a scalar to a package. The basic Tie::Scalar package provides a new method, as well as methods TIESCALAR, FETCH and STORE. The *Tie::StdScalar* package provides all the methods specified in *Note Perltie: (perl.info)perltie,. It inherits from Tie::Scalar and causes scalars tied to it to behave exactly like the built-in scalars, allowing for selective overloading of methods. The new method is provided as a means of grandfathering, for classes that forget to provide their own TIESCALAR method. For developers wishing to write their own tied-scalar classes, the methods are summarized below. The *Note Perltie: (perl.info)perltie, section not only documents these, but has sample code as well: TIESCALAR classname, LIST The method invoked by the command `tie $scalar, classname'. Associates a new scalar instance with the specified class. LIST would represent additional arguments (along the lines of *Note AnyDBM_File: AnyDBM_File, and compatriots) needed to complete the association. FETCH this Retrieve the value of the tied scalar referenced by *this*. STORE this, value Store data value in the tied scalar referenced by *this*. DESTROY this Free the storage associated with the tied scalar referenced by *this*. This is rarely needed, as Perl manages its memory quite well. But the option exists, should a class wish to perform specific actions upon the destruction of an instance. MORE INFORMATION ================ The *Note Perltie: (perl.info)perltie, section uses a good example of tying scalars by associating process IDs with priority.  File: pm.info, Node: Tie/Scalar/Timeout, Next: Tie/SecureHash, Prev: Tie/Scalar, Up: Module List Scalar variables that time out ****************************** NAME ==== Tie::Scalar::Timeout - Scalar variables that time out SYNOPSIS ======== use Tie::Scalar::Timeout; tie my $k, 'Tie::Scalar::Timeout', EXPIRES => '+2s'; $k = 123; sleep(3); # $k is now undef tie my $m, 'Tie::Scalar::Timeout', NUM_USES => 3, VALUE => 456; tie my $n, 'Tie::Scalar::Timeout', VALUE => 987, NUM_USES => 1, POLICY => 777; tie my $p, 'Tie::Scalar::Timeout', VALUE => 654, NUM_USES => 1, POLICY => \&expired; sub expired { $is_expired++ } DESCRIPTION =========== This module allows you to tie a scalar variable whose value will be reset (subject to an expiry policy) after a certain time and/or a certain number of uses. One possible application for this module might be to time out session variables in mod_perl programs. When tying, you can specify named arguments in the form of a hash. The following named parameters are supported: EXPIRES Use EXPIRES to specify an interval or absolute time after which the value will be reset. (Technically, the value will still be there, but the module's FETCH sub will return the value as dictated by the expiry policy.) Values for the EXPIRES field are modelled after Netscape's cookie expiration times. Except, of course, that negative values don't really make sense in a universe with linear, one-way time. The following forms are all valid for the EXPIRES field: +30s 30 seconds from now +10m ten minutes from now +1h one hour from now +3M in three months +10y in ten years time 25-Apr-2001 00:40:33 at the indicated time & date Assigning a value to the variable causes EXPIRES to be reset to the original value. VALUE Using the VALUE hash key, you can specify an initial value for the variable. `NUM_USES' Alternatively or in addition to EXPIRES, you can also specify a maximum number of times the variable may be read from before it expires. If both EXPIRES and `NUM_USES' are set, the variable will expire when either condition becomes true. If `NUM_USES' isn't set or set to a negative value, it won't influence the expiry process. Assigning a value to the variable causes `NUM_USES' to be reset to the original value. POLICY The expiration policy determines what happens to the variable's value when it expires. If you don't specify a policy, the variable will be undef after it has expired. You can specify either a scalar value or a code reference as the value of the POLICY parameter. If you specify a scalar value, that value will be returned after the variable has expired. Thus, the default expiration policy is equivalent to POLICY => undef If you specify a code reference as the value of the POLICY parameter, that code will be called when the variable value is FETCH()ed after it has expired. This might be used to set some other variable, or reset the variable to a different value, for example. BUGS ==== None known so far. If you find any bugs or oddities, please do tell me about them. AUTHOR ====== Marcel GrEnauer COPYRIGHT ========= Copyright 2000 Marcel GrEnauer. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. SEE ALSO ======== perl(1), Tie::Scalar(3pm).  File: pm.info, Node: Tie/SecureHash, Next: Tie/SentientHash, Prev: Tie/Scalar/Timeout, Up: Module List A tied hash that supports namespace-based encapsulation ******************************************************* NAME ==== Tie::SecureHash - A tied hash that supports namespace-based encapsulation VERSION ======= This document describes version 1.00 of Tie::SecureHash, released December 3, 1998 SYNOPSIS ======== use Tie::SecureHash; # CREATE A SECURE HASH my %hash; tie %hash, Tie::SecureHash; # CREATE A REFERENCE TO A SECURE HASH (BLESSED INTO Tie::SecureHash!) my $hashref = Tie::SecureHash->new(); # CREATE A REFERENCE TO A SECURE HASH (BLESSED INTO $some_other_class) my $hashref = Tie::SecureHash->new($some_other_class); # CREATE NEW ENTRIES IN THE HASH package MyClass; sub new { my ($class, %args) = @_ my $self = Tie::SecureHash->($class); $self->{MyClass::public} = $args{public}; $self->{MyClass::_protected} = $args{protected}; $self->{MyClass::__private} = $args{private}; return $self; } # SAME EFFECT, EASIER SYNTAX... package MyClass; sub new { my ($class, %args) = @_ my $self = Tie::SecureHash->($class, public => $args{public}, _protected => $args{protected}, __private => $args{private}, ); return $self; } # ACCESS RESTRICTIONS ON ENTRIES package MyClass; sub print_attributes { my $self = $_[0]; # OKAY? (ACCESSIBLE WHERE?) print $self->{public}; # YES (ANYWHERE) print $self->{_protected}; # YES (ONLY IN MyClass HIERARCHY) print $self->{__private}; # YES (ONLY IN MyClass) } package SonOfMyClass; @ISA = qw( MyClass ); sub print_attributes { my $self = $_[0]; # OKAY? (ACCESSIBLE WHERE?) print $self->{public}; # YES (ANYWHERE) print $self->{_protected}; # YES (ONLY IN MyClass HIERARCHY) print $self->{__private}; # NO! (ONLY IN MyClass) } package main; my $object = MyClass->new(); # OKAY? (ACCESSIBLE WHERE?) print $object->{public}; # YES (ANYWHERE) print $object->{_protected}; # NO! (ONLY IN MyClass HIERARCHY) print $object->{__private}; # NO! (ONLY IN MyClass) # DEBUGGING $object->Tie::SecureHash::debug(); DESCRIPTION =========== [Coming soon] DIAGNOSTICS =========== `Private key %s of tied securehash inaccessible from package %s' Private keys can only be accessed from their "owner" package. An attempt was made to access a private key from some other package. `Private key %s of tied securehash inaccessible from file %s' Private keys can only be accessed from the lexical scope of the file in which they were originally declared. An attempt was made to access a private key from some lexical scope (probably another file, but perhaps an eval). `Protected key %s of tied securehash inaccessible from package %s' Protected keys can only be accessed from theie "owner" package and any of its subclasses. An attempt was made to access a protected key from some package not in the owner's inheritance hierarchy. `Entry for key %s of tied securehash cannot be created from package %s' Keys must be declared from within the lexical scope of their owner's package. In other words, the qualifier for a key declaration must be the same as the current package. An attempt was made to declare a key from some package other than its owner. `Private key %s does not exist in tied securehash' Securehash keys are not autovivifying; they must be declared using a fully qualified key before they can be used. An attempt was made to access or assign to an unqualified private key (one with two leading underscores), before the corresponding fully qualified key was declared. `Protected key %s does not exist in tied securehash' Securehash keys are not autovivifying; they must be declared using a fully qualified key before they can be used. An attempt was made to access or assign to an unqualified protected key (one with a single leading underscore), before the corresponding fully qualified key was declared. `Public key %s does not exist in tied securehash' Securehash keys are not autovivifying; they must be declared using a fully qualified key before they can be used. An attempt was made to access or assign to an unqualified public key (one with no leading underscore), before the corresponding fully qualified key was declared. `Ambiguous key %s (when accessed from package %s). Could be: %s' An unqualified key was used to access the securehash, but it was ambiguous in the context. The error message lists the set of fully qualified keys that might have matched. `Invalid key %s' An attempt was made to access the securehash (or declare a key) through an improperly formatted key. This almost always means that the qualifier isn't a valid package name. `%s can't be both "strict" and "fast"' Tie::SecureHash detected that both the $Tie::SecureHash::strict and $Tie::SecureHash::fast keys were set. But the two modes are mutually exclusive. `Accessing securehash via unqualified key %s will be unsafe in 'fast' mode. Use %s::%s' This warning is issued in "strict" mode, and points out an access attempt which will break if the code is converted to "fast" mode. `Tie'ing a securehash directly will circumvent 'fast' mode. Use Tie::SecureHash::new instead' This warning is issued in "strict" mode, and points out an explicit tie to the Tie::SecureHash module. Hashes tied in this way will not speed up under "fast" mode. `Tie'ing a securehash directly should never happen in 'fast' mode. Use Tie::SecureHash::new instead' This warning is issued in "fast" mode, and points out an explicit tie to the Tie::SecureHash module. Hashes tied in this way will still be slow. This diagnostic can be turned off by setting $Tie::SecureHash::fast to any value other than 1. `Unable to assign to securehash because the following existing keys are inaccessible from package %s and cannot be deleted: %s' An attempt was made to assign a completely new set of entries to a securehash. Typically something like this: %securehash = (); This doesn't work unless all the existing keys are accessible at the point of the assignment. AUTHOR ====== Damian Conway (damian@cs.monash.edu.au) BUGS AND IRRITATIONS ==================== There are undoubtedly serious bugs lurking somewhere in this code :-) Bug reports and other feedback are most welcome. COPYRIGHT ========= Copyright (c) 1998-2000, Damian Conway. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)