Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • You could do something like what Win32::TieRegistry does, and create a tied hash class which just accepts a delimited string as a hash key, but internally breaks it up into separate keys. That is, if there isn't already a generic module which does this :-)
    • And on that note, here's a very incomplete tied hash class. Possible improvements (besides making it a complete tied hash class), might be to add options for recursively making tied hashes, so you could say something like: $href = $hash{"A:B"}; $value = $href->{"C:D"}; (Note: the way it is now, only the top level hash is tied).
      #!/usr/bin/perl

      use strict;
      use warnings;
      use Data::Dumper;

      package Tie::Hash::DelimitedKey;

      sub TIEHASH {
        my ($class, $delimiter) = @_;
        $delimiter = ":" unless defined $delimiter;
        my $re = qr/\Q$delimiter/ unless ref($delimiter);
        bless {DELIM=>$re, HASH=>{}}, $class;
      }

      sub STORE {
        my $self = shift;
        my ($href, $last_key) = $self->_walk_keys(shift);
        $href->{$last_key} = shift;
      }

      sub FETCH {
        my $self = shift;
        my ($href, $last_key) = $self->_walk_keys(shift);
        $href->{$last_key};
      }

      sub _walk_keys {
        my ($self, $key) = @_;
        my $href = $self->{HASH};
        my @keys = split $self->{DELIM}, $key;
        my $last_key = pop @keys;
        for (@keys) {
          $href->{$_} = {} unless exists $href->{$_};
          $href = $href->{$_};
        }
        return $href, $last_key;
      }

      package main;
      my $href = tie my %hash, 'Tie::Hash::DelimitedKey';

      $hash{"A:B:C:D"} = 5;
      print $hash{"A:B:C:D"},"\n";
      my $sref = \$hash{"A:B:C:D"};
      $$sref = 6;
      print Dumper($href);