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

Hello Monks, I am working on a script that gets by DBI an hash ref inside an array ref. To get the field names of the SQL result I have to dereference the hash ref inside the array ref, so I can go thru any field name using foreach. No problem so long, I using the following code for doing that:

foreach my $head (@{$sth->{NAME_uc}}) { print $head . "\n"; }

But as I remember from the Alpaca book I mixed up two syntax styles. Each for the array ref and the hash ref. So my question now: How look the pretty code for the dereferencing in the above code?

Thanks, so long!

Replies are listed 'Best First'.
Re: Dereferencing a hash ref in an array ref
by moritz (Cardinal) on Mar 26, 2010 at 08:05 UTC
    But as I remember from the Alpaca book I mixed up two syntax styles.

    Right. But there's nothing wrong with that. I think what you have is quite readable already, though of course you can use a bit more whitespace.

    Perl 6 - links to (nearly) everything that is Perl 6.

      Okay, thanks anyway. (De)Referencing in more than one "level" is quite hard for me.

      Greetings, Schaelle

Re: Dereferencing a hash ref in an array ref
by Anonymous Monk on Mar 26, 2010 at 07:34 UTC
    What is pretty?
    print join "\n", @{ $sth->{NAME_uc} }, '';

      I just meant that the dereferencing using for the array deref the curly brackets, and for the hash deref the dereferencing using the arrow syntax. I thought its better only to use the second one, but dont know how that have to look like.

      Part 1:

      @{$hashref}

      Part 2 ("$hashref"):

      $sth->{NAME_uc}

      If thats already "pretty" (one syntax style for dereferencing) my thoughts just were wrong, would be an answer too.

      Greetings, Schaelle

        :) use Anonymous::Monk; no ESP;

        References quick reference

        You can only get scalars using the arrow syntax, you cant get multiple values

        my $sth = { NAME_uc => [ 1 .. 2 ] }; print join "\n" , $sth->{NAME_uc}[0 ,1 ]; __END__ 2
        my $sth = { NAME_uc => [ 1 .. 2 ] }; print join "\n" , @$sth->{NAME_uc}[0 ,1 ]; __END__ Not an ARRAY reference at - line 3.
        That is why you need curlies
        my $sth = { NAME_uc => [ 1 .. 2 ] }; print join "\n" , @{ $sth->{NAME_uc} } [0 ,1 ]; __END__ 1 2
        The arrow-less way
        my $sth = { NAME_uc => [ 1 .. 2 ] }; print join "\n" , @{ $$sth{NAME_uc} } ,'' __END__ 1 2
        References quick reference