Slash Boxes
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.
More | Login | Reply
Loading... please wait.
  • It's interesting to see that structure. It's similar to what I did in a mysql database in that the child had a field for it's parent. In hindsight maybe I should have created another field that listed the geneology of the child. I seemed to be determining the parents of a child much more than the children of a parent.

  • Well, go ahead and do this with eval if you're not concerned with either speed or security.

    Eval means you're firing up the compiler. Fun fun. Slow slow.

    Eval also means that you have to be very careful about the data. It'd be trivial to launch arbitrary code by selecting the proper data here.

    There's really no need. You can run a lot faster and a lot safer with:

    $tree ||= {};
    my $place = $tree;
    $place = $place->{$_} ||= {} for split /:/, $path;

    (This may not be precisely the code, but this seemed t

    • Randal L. Schwartz
    • Stonehenge
    • $tree ||= {};
      my $place = $tree;
      $place = $place->{$_} ||= {} for split /:/, $path;

      Something like that lets you end with a HASHref instead of the SCALARref. Unfortunately, you can't create a reference to a hash element's value part.

      But adding something like a _value key solves that:

      sub walk_tree {
          my ($hashref, @path) = @_;
          $hashref = \%{ $hashref->{$_} } for @path;
          return $hashref;
      my $tree = {};
      ${ walk_tree $tree => qw(A B C) }{_value} = "value";

  • 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).


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

      package Tie::Hash::DelimitedKey;

      sub TIEHASH {
        my ($class, $delimiter) = @_;
        $delimiter = ":" unless defined