How come everyone else gets to have the fun? Let's see if you'll let me in with this little hack that lets you play with all sorts of mixtures of structures...hashes, and arrays, and anonymous subs...OH MY! And in case something goes haywire and the key you specify doesn't exist [:'(] have no fear, it just returns undef and allows you to go along on your merry way! Follow the yellow br...err...I mean...umm...here's the code:

#!/usr/bin/perl require 5.6.1; use strict; my $hash; $hash = { a => { b=> [ \\\$hash, { c => sub { $_ = shift; return [ join "","j",$_,"h" ]; } } ] } }; sub retrievekey { my $endvalue = shift; my $keys = shift; my @keys = split /\./, $keys; foreach my $x (@keys) { return undef unless defined $endvalue; $endvalue = $$endvalue while (ref($endvalue) eq "REF"); eval { if (ref($endvalue) eq "HASH") { $endvalue = $endvalue->{$x}; } elsif (ref($endvalue) eq "ARRAY") { $endvalue = $endvalue->[$x]; } elsif (ref($endvalue) eq "CODE") { $endvalue = $endvalue->($x); } else { return undef; } }; return undef if ($@); } $endvalue; } print retrievekey($hash, 'a.b.0.a.b.1.c.ap.0'),$/; __DATA__ output: japh

Hey, it derefs any references to references and follows paths for hashes, arrays, and subs. This is just a silly bit of fun. Of course, don't use this or whoever maintains the code will hunt you down and shoot you... and nobody wants that... at least I don't :-P

antirice    
The first rule of Perl club is - use Perl
The
ith rule of Perl club is - follow rule i - 1 for i > 1


In reply to Re: quick question about hash element access by antirice
in thread quick question about hash element access by glwtta

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.