Search code examples
perldata-dumper

how do I access this item?


I am using Data::Dumper. My code is:

use Data::Dumper;
blah, blah, blah.....
print Dumper \@data;

My output is:

$VAR1 = [
      [
        'Dave',
        'Green',
        '5',
      ],
      [
        'Bob',
        'Yellow',
        '4',
      ]
    ];

How do I access 'Bob' or '5'? Also, how can I turn @data into a hash or variable in order to put the entire contents into a database?

EDIT: @data is created from reading the contents of a file:

while (<PARSE>) {
    push @data, [unpack $template, $_]
}

Solution

  • #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    my @data = ( [ 'Dave', 'Green', '5', ], [ 'Bob', 'Yellow', '4', ] );
    print $data[0]->[2], "\n";  # 5
    print $data[1]->[0], "\n";  # Bob
    

    @data is an array of arrays. A hash consists of a key and a corresponding value. In order to convert the array into a hash, you have to assign one of the elements to be the key and the rest the value.

    Note

    Alternative syntax:

    $data[0]->[1] is equivalent to $data[0][1].

    Refer

    Acknowledgements:

    Bill Ruppert and Joel.