perldata-dumper

Print data after dumper


I have this structure with data-dumper:

$VAR1 = {
      'field' => [
                 {
                   'content' => {
                                'en' => [
                                        'Footware haberdashery leather goods'
                                      ],
                                'de' => [
                                        'Schuhe Kurzwaren und Lederartikel'
                                      ],
                                'it' => [
                                        'Calzature mercerie e pelletterie'
                                      ]
                              },
                   'type' => 'tag',
                   'valore' => 'TAG3'
                 },
                 {
                   'content' => {
                                'en' => [
                                        'Cobbler'
                                      ],
                                'de' => [
                                        'Schuster'
                                      ],
                                'it' => [
                                        'Calzolai'
                                      ]
                              },
                   'type' => 'tag',
                   'valore' => 'TAG24'
                 }
               ]
    };

My question is: how to take data and print one for one ? I want print the name, the tag and valore. For my software is necessary take the name of shop and more data for example the type


Solution

  • It looks like the structure is a hashref containing an arrayref of hashes, and so on. And apparently where you mention 'name' you mean 'content' by language. Likewise, it seems that where you mention 'tag' you mean 'type'. My answer will be based on those assumptions.

    foreach my $rec (@{$href->{field}}) {
        print "$rec->{content}->{en}->[0]: $rec->{type}, $rec->{valore}\n";
    }
    

    The -> between {content} and {en}, and again between {en} and [0] are optional, and a matter of style.

    If you simply want to access elements directly (foregoing the loop), you might do it like this:

    print $href->{field}->[0]->{content}->{en}->[0], "\n";
    print $href->{field}->[0]->{type}, "\n";
    print $href->{field}->[0]->{valore}, "\n";
    

    If you want to print all the languages, you could do this:

    foreach my $rec (@{$href->{field}}) {
        print $rec->{content}->{$_}->[0], "\n" foreach sort keys %{$rec->{content}};
        print $rec->{type}, "\n";
        print $rec->{valor}, "\n\n";
    }
    

    There are several Perl documentation pages that could be of use to you in the future as you learn to manipulate references and datastructures with Perl: perlreftut, perlref, and perldsc. Access them from your own system as perldoc perlreftut, for example.