http://qs321.pair.com?node_id=1035713


in reply to Access to hash ref element

Seems to be a popular question for newcomers to ask how to access some component of a complicated structures.

The answer is to user the built-in debugger.

tlegrady@rw-q318:~$ perl -d t.pl Loading DB routines from perl5db.pl version 1.3 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(t.pl:5): my $data = [ DB<1> n main::(t.pl:16): my $test = $data->{ name }; DB<1> x $data 0 ARRAY(0x70b910) 0 HASH(0x70b970) 'name' => 'Mary' DB<2> x $data->[0] 0 HASH(0x70b970) 'name' => 'Mary' DB<3> x $data->[0]{name} 0 'Mary'

When the debugger starts, it shows that it's about to execute line 5. I do a "next" ( 'n') to complete that, and then it's going to execute line 16. I query the debugger to show the value of $data, and then of its components. Since you're looking right at it, it's easy to tell you want array element '0', hash tag 'name'.

As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Replies are listed 'Best First'.
Re^2: Access to hash ref element
by davido (Cardinal) on May 28, 2013 at 20:05 UTC

    Another "answer" is simply Data::Dumper. It produces a dump that shows both the structure's content, and how to access individual elements. All that needs to be done is to dump the structure, and see how it's built.


    Dave

Re^2: Access to hash ref element
by Laurent_R (Canon) on May 28, 2013 at 21:45 UTC

    I fully agree. The debugger (and especially the x command to unfold data structure) is of tremendous help for all such cases and has helped me out many times. But, for some reason, many people seem to be afraid to use it, although it is in fact a very simple tool to use. Many questions on many developping forums would never be asked if the OP had "dared" to use the debugger to figure out what is going on. But there is nothing "daring" there, and it is increedibly helpful.

    Having said that, the Data::Dumper is also a very useful way of understanding complicated data structure. But for the purpose of debugging, I think the debugger is the right tool.

      the debugger may be great for debugging your own programs, but not particularly friendly for sharing on forums -- Dumper fits that bill better

        Sure, but the OP was asking about his or her own program, or am I wrong?

        And, actually, thinking about it, I don't really agree. I also use the debugger to test code lines used by posters. And it is often quite useful to do that. And faster than saving code and testing it.