[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] My little trick for the day



On Wed, Feb 16, 2000 at 09:47:56AM -0600, Andy Lester wrote:
> So now, my module dies if somehow I have dupe keys in my lookup table, and
> I don't have to worry about keeping everything dupe-free by eyeball.

Here's some overkill, how about a tied hash?

package Tie::Hash::Nodups;

use base qw(Tie::StdHash);

sub TIEHASH {
        my $class = shift;
        my $self = bless {}, $class;
        my @list = @_;
        if( @list % 2 ) {
                require Carp;
                Carp::croak("Odd number of elements in hash assignment");
        }
        for( $idx = 0; $idx <= $#list; $idx += 2 ) {
                my($key, $val) = @list[$idx, $idx+1];
                if( exists $self->{$key} ) {
                        require Carp;
                        Carp::carp("Duplicate key '$key' found.");
                }
                $self->{$key} = $value;
        }
        return $self;
}


Then you can say:
        tie %stuff, 'Tie::Hash::NoDup', (FU => 'Foo',
                                         MU => 'Moo',
                                         FU => 'Fu');

Of course, then %stuff has all the wonderful zip and speed of a snail caught
in molasses in Feburary (due to the sluggishness of the tie interface)

-- 

Michael G Schwern                                           schwern@pobox.com
                    http://www.pobox.com/~schwern
     /(?:(?:(1)[.-]?)?\(?(\d{3})\)?[.-]?)?(\d{3})[.-]?(\d{4})(x\d+)?/i

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe