#1
  1. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,571
    Rep Power
    595

    Foreach and referencing complex hashes


    I can never seem to get my head around hash references and need some help. I have an XML hash and I need to process a set of sub-hashes (is that a valid term?). Here is my current non-working loop:
    Code:
    foreach my $id (%{$xml->{children}->{content}}) {
            print($id->{title}."\n");
    }
    The reference $xml->{children}->{content} is a series of hash keys (ids). Among the elements of each is 'title' ($xml->{children}->{content}->{<some id>}->{title}) and that is what I want to extract. However, I cannot come up with the syntax that gets the hash rather than the key. Can someone give me the correct syntax to do what I want? TIA.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,571
    Rep Power
    595
    Never mind. I got it, sheesh!
    Code:
    foreach my $id (keys %{$xml->{children}->{content}}) {
            print($xml->{children}->{content}->{$id}->{title}."\n");
    }
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,264
    Rep Power
    1810
    I expect that you can drop most of the arrows.

    Code:
    foreach my $id (keys %{$xml->{children}{content}}) {
            print($xml->{children}{content}{$id}{title}."\n");
    }
    When you have a reference, only the first arrow is necessary.

    Also, this might not be helpful, but when you are reaching into such deeply nested structures, and the thing you want to work with isn't the key, you can pull out just the hash or element you want to work with.

    Example:

    Code:
    foreach my $content (values %{$xml->{children}{content}}) {
            print($content->{title}."\n");
    }
    By asking for the value, you can put that into a variable and have a direct reference to the hash you need to work with without having to reference the entire structure each time.

    Comments on this post

    • gw1500se agrees : Thanks.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,571
    Rep Power
    595
    Ah ha! Values was what I was really looking for to eliminate all that repeated nesting. Thanks.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.

IMN logo majestic logo threadwatch logo seochat tools logo