hperange:

I generally avoid that practice, as it's easy to get confused. Sometimes I want a shorthand variable for a member, like color, but also want to use the hashref, too. In that case, I normally have two variables $rColor and $color, where $rColor is the reference. This keeps them visually distinct, but related (to me, anyway). If I wasn't using the reference, I'd avoid the issue altogether by making a subroutine that simply returned the color:

$class = '...'; $color = color_of($class); sub color_of { $class = shift; my $t = first { $class =~ /$_->{'re'}/ } @rules; return $color->{'color'}; }

Having said all that, it really depends on usage. I occasionally find it more convenient to reuse the variable. In limited scope, it can often be clear and obvious enough to not warrant the extra effort:

for my $foo (...) { my $color = first { $class =~ /$_->{'re'}/ } @rules; $color = $color->{'color'}; ... }

With this bit, I'm setting up the variable at the top of the loop, so it's clear (to me) that the first line is simply an interim step. If the for body were longer, and I switched between the hash version and scalar version, it would be confusing. In this case, it would be nice if there were a simple way to do it in one go, like:

my $color = ${first { $class =~ /$_->{'re'}/ } @rules}->{'color'};

But if it exists, then I haven't found it.

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: Data structure / hash reference question by roboticus
in thread Data structure / hash reference question by hperange

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.