Guildencrantz has asked for the wisdom of the Perl Monks concerning the following question:

Okay, I'm trying to dereference an array of hash refs, and I can do it. But it takes two statements! The horror is mind boggling.
I think I've been staring at this too long and now I need help. My working code is this:
my $rowhash = (fetchrow_hashref($dbh, $query))[0]; print $$rowhash{'Msg_type'}, "\n";
and it works just fine. I get the hashed value that I'm looking for. My question is: Can't this be done on a single line? Can't I dereference the fetchrow() return all at once? I've been playing with this for a while and can't seem to get it to work.
Thanks for your shared wisdom,
~~Guildencrantz

Replies are listed 'Best First'.
Re: Dereferencing array of hashrefs
by blokhead (Monsignor) on May 12, 2004 at 23:52 UTC
    The expression (fetchrow_hashref($dbh, $query))[0] evaluates to a hashref. You can dereference a key from any hashref by using EXPR->{key}. You can also omit the arrow operator if EXPR ends with an array or hash index.

    Putting that together gives:

    print +(fetchrow_hashref($dbh, $query))[0]{key}, "\n";
    You need the + to disambiguate the expression from print(). All in all, it's a little messy, and having the extra variable is a reasonable tradeoff for readability.

    Update: ysth is dead on, you do need the arrow!

    blokhead

      You can also omit the arrow operator if EXPR ends with an array or hash index.
      An array or hash index, yes, but not a list slice; here you do need the ->.
      Thanks!
      I would like to note that your consolidated version isn't working. It keeps kicking the error:
      syntax error at ./script.pl line 43, near "){" Execution of ./script.pl aborted due to compilation errors.
      However the expanded EXPR->{key} version works fabulously. I do agree that it's a bit ambiguous, but I find it more fitting in this particular instance.
      Again, thanks.
      ~~Guildencrantz