Well this whole discussion led off to the thread of why what I was doing originally was unsafe and slow. So I thought I would post this, which I hope is safe, if not fast. It's a way of getting from a string to a reference into a particular key of a hash. You can specify which hashes you want to be referenceable.

update: demoronified the code in one place

sub string_to_struct { my $string = shift; my ($var, $keys) = split /-/, $string, 2; $keys = "-$keys"; # you could use a lookahead in the split, but in my + experience they break on older Perl 5s. return 0 unless ( $var eq "safe" or $var eq "alsosafe" ); $change{$var}++; # global no strict refs; my $ref = $$var; # reference to the original. can alter the original use strict refs; return deref($ref, $keys); } sub deref { return \$_[0] unless $_[1] =~ s/^-([\w_]+)//; deref ($_[0]->{$1}, $_[1]); }

This should take e.g. safe-foo-bar and return a reference to $safe->{foo}{bar}. Comments are welcome - it's the result of a lot of debugging, so probably not the most elegant in the world!

I also asked about the reverse process. I'm still not sure there's a way to get from a particular hash key to a string representing it, i.e. from $safe->{foo}{bar} to safe-foo-bar. At least not if you use a subroutine. The subroutine just gets the value of $safe->{foo}{bar}. It gets it by reference, but it still doesn't know where the reference "is". I suppose you could pass it like this:

struct_to_string($safe,$safe->{foo},$safe->{foo}{bar});
and do something with the list of values, but by that time, you may as well type it yourself...

Thanks for all the help.
dave hj~


In reply to Re: stringification by dash2
in thread stringification by dash2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.